【问题标题】:Dictionary comprehension with if statements using list comprehension使用列表推导的 if 语句的字典推导
【发布时间】:2018-07-06 00:08:14
【问题描述】:

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

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 语句被评估为 OR 语句,而我希望它被评估为 AND 语句。所以我只想找回 id1 字典。我想回来:

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

【问题讨论】:

  • 你能显示你想要的输出应该是什么吗?

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


【解决方案1】:

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

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

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

注意如果match_list的key和feature_list一样,那就更简单了,只需要比较字典即可:

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

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

【讨论】:

  • 完美——知道有一个优雅的解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-19
  • 2022-01-13
相关资源
最近更新 更多