我有一个有序的字典如下:
MY_ORDERED_DICT = OrderedDict([
('table1', {
'required': True,
'col': OrderedDict([
('id', 'aaa'),
('registration_date', 'aaa'),
('date_of_birth', 'aaa'),
])
}),
('table2', {
'required': True,
'col': OrderedDict([
('product_id', 'aaa'),
('id', 'aaa'),
('datetime', 'aaa'),
('quantity', 'aaa'),
])
}),
('table3', {
'required': False,
'col': OrderedDict([
('product_id', 'aaa'),
('brand', 'aaa'),
('name', 'aaa'),
])
}),
('table4', {
'required': False,
'col': OrderedDict([
('campaign_id', 'aaa'),
('id', 'aaa'),
('datetime', 'aaa'),
])
}),
('table5', {
'required': False,
'col': OrderedDict([
('c_id', 'aaa'),
('id', 'aaa'),
('datetime', 'aaa'),
])
})
])
从这个 OrderedDict中,我想提取具有包含字符串id
和datetime
的列(也是 OrderedDict(字段的键。
我这样做如下:
list(map(lambda element: element[0], filter(lambda cel: {'id', 'datetime'}.issubset(set(cel[1]['col'])), MY_ORDERED_DICT.items())))
而且它似乎工作得很好。 它确实返回:
['table2', 'table4', 'table5']
我的问题是,我担心索蒙会看它并告诉我它太复杂了。
我正在寻找灵感,以更优雅的方式做到这一点。
不要使用map()
,当列表理解会更清晰时filter()
:
[
key for key, value in MY_ORDERED_DICT.items()
if {"id", "datetime"} <= value["col"].keys()
]
请注意,键字典视图也是一个集合,您可以使用<=
或>=
运算符测试字典是否具有最小键集,以确定其中一个是子集还是超集。
上面的操作与代码相同的工作,因此生成相同的输出:
>>> [
... key for key, value in MY_ORDERED_DICT.items()
... if {"id", "datetime"} <= value["col"].keys()
... ]
['table2', 'table4', 'table5']