使用list comprehension的if语句的字典理解

时间:2018-01-26 15:59:32

标签: python dictionary if-statement list-comprehension dictionary-comprehension

我正在尝试根据另一个字典中的值过滤大字典。我想存储要在列表中过滤的键。到目前为止,我有:

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

这将返回所有id,因为我认为当我希望将if语句作为AND语句进行求值时,if语句被评估为OR语句。所以我只想要回id1字典。我想回来:

filtered_dict = {'id1': {'a': 1,
                         'b': 2,
                         'c': 3}}

1 个答案:

答案 0 :(得分:3)

你是对的:你的测试总是通过,因为一个条件是真的。你需要所有的条件都是真的。

您可以使用all来获得正确的行为:

{k: v for k, v in all_dict.items() if all(v[feature] == match_dict[feature] for feature in feature_list)}

请注意,如果match_list密钥与feature_list相同,则更简单,只需比较字典:

r = {k: v for k, v in all_dict.items() if v == match_dict}

(或使用您首先需要的功能计算已过滤的match_dict。效果会更好)

相关问题