使用列表理解的if语句进行字典理解 [英] Dictionary comprehension with if statements using list comprehension
问题描述
我正在尝试根据另一个词典中的值来过滤大型词典。我想存储要在列表中进行过滤的键。到目前为止,我有:
feature_list = ['a','b','c']
$ p,则为feature_list中的feature的all_dict.items()中的v $ p>
match_dict = {'a':1,1,
'b':2,
'c':3}
all_dict = {'id1':{'a':1,
'b':2,2,
'c':3},
'id2':{'a':1,1,
'b':4,
' c':3},
'id3':{'a':2,
'b':5,
'c':3}}
filterd_dict = {k:v为k,如果
v [feature] == match_dict [feature]}
这将返回所有id,因为当我希望将if语句视为AND语句时,将if语句视为OR语句。所以我只想要id1字典。我想回来:
filtered_dict = {'id1':{'a':1,
' b':2,
'c':3}}
解决方案您是对的:您的测试始终会通过,因为一个条件为真。您需要满足所有条件。
您可以使用
all
来获得正确的行为:{k:v为k,v在all_dict.items()中,如果all(v [feature] == match_dict [feature] for feature在feature_list中)}
请注意,如果
match_list
密钥与feature_list
相同,它甚至更简单,只需比较字典即可:r = {k:v表示k,v表示all_dict.items(),如果v == match_dict}
(或使用您首先需要的功能计算经过过滤的
match_dict
。性能会更好)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. So I only want back the id1 dictionary. 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:{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 asfeature_list
, it's even simpler, just compare dictionaries: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)这篇关于使用列表理解的if语句进行字典理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!