繁体   English   中英

使用列表理解的if语句进行字典理解

[英]Dictionary comprehension with if statements using list 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}}

您是对的:您的测试始终会通过,因为一个条件成立。 您需要满足所有条件。

您可以使用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 。性能会更好)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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