[英]Dictionary comprehension with if statements using list comprehension
I am trying to filter a large dictionary based on values from another dictionary. 我正在尝试根据另一个字典中的值来过滤大型字典。 I want to store the keys to filter on in a list.
我想存储要在列表中进行过滤的键。 So far I have:
到目前为止,我有:
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]}
This returns all the ids because I think the if statement is been evaluated as an OR statement when I would like it to be evaluated as an AND statement. 这将返回所有id,因为当我希望if语句被评估为AND语句时,我认为if语句被评估为OR语句。 So I only want back the id1 dictionary.
所以我只想要id1字典。 I would like to get back:
我想回来:
filtered_dict = {'id1': {'a': 1,
'b': 2,
'c': 3}}
You're right: your test always passes because one condition is true. 您是对的:您的测试始终会通过,因为一个条件成立。 You need all the conditions to be true.
您需要满足所有条件。
You could use all
to get the proper behaviour: 您可以使用
all
来获得适当的行为:
{k: v for k, v in all_dict.items() if all(v[feature] == match_dict[feature] for feature in feature_list)}
note that if match_list
keys are the same as feature_list
, it's even simpler, just compare dictionaries: 请注意,如果
match_list
键与feature_list
相同,则更为简单,只需比较字典即可:
r = {k: v for k, v in all_dict.items() if v == match_dict}
(or compute a filtered match_dict
with the features you require first. Performance will be better) (或使用您首先需要的功能来计算过滤后的
match_dict
。性能会更好)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.