vendredi 26 janvier 2018

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


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

Aucun commentaire:

Enregistrer un commentaire