使用列表理解的 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]}
这 returns 所有 id 因为我认为 if 语句被评估为 OR 语句,而我希望它被评估为 AND 语句。所以我只想返回 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
。性能会更好)
我正在尝试根据另一个字典中的值过滤一个大字典。我想将要过滤的键存储在列表中。到目前为止我有:
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]}
这 returns 所有 id 因为我认为 if 语句被评估为 OR 语句,而我希望它被评估为 AND 语句。所以我只想返回 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
。性能会更好)