Dictionary comprehension with if statements using list comprehension

三世轮回 提交于 2020-07-21 07:26:21

问题


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}}

回答1:


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 as feature_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)



来源:https://stackoverflow.com/questions/48464958/dictionary-comprehension-with-if-statements-using-list-comprehension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!