【发布时间】:2018-07-06 00:08:14
【问题描述】:
我正在尝试根据另一个字典中的值过滤大型字典。我想将要过滤的键存储在列表中。到目前为止,我有:
feature_list = ['a', 'b', 'c']
match_dict = {'a': 1,
'b': 2,
'c': 3}
all_dict = {'id1': {'a': 1,
'b': 2,
'c': 3},
'id2': {'a': 1,
'b': 4,
'c': 3},
'id3': {'a': 2,
'b': 5,
'c': 3}}
filtered_dict = {k: v for k, v in all_dict.items() for feature in feature_list if
v[feature] == match_dict[feature]}
这会返回所有 id,因为我认为 if 语句被评估为 OR 语句,而我希望它被评估为 AND 语句。所以我只想找回 id1 字典。我想回来:
filtered_dict = {'id1': {'a': 1,
'b': 2,
'c': 3}}
【问题讨论】:
-
你能显示你想要的输出应该是什么吗?
标签: python dictionary if-statement list-comprehension dictionary-comprehension