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