简体   繁体   中英

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. 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 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM