繁体   English   中英

从字典列表中过滤键值

[英]Filter key-values from a list of dictionaries

我有一个字典列表,我需要过滤某个键具有特定值的列表。 例如,只有dict s where 'name' is 'Joel' or 'Ellie'

dict1 = {'name': 'Joel', 'age': 48, 'brother': 'Tommy'}
dict2 = {'name': 'Tommy', 'age': 43, 'brother': 'Joel'}
dict3 = {'name': 'Ellie', 'age': 14, 'brother': None}

list_of_dicts = [dict1, dict2, dict3]

# <output>
[{'name': 'Joel', 'age': 48, 'brother': 'Tommy'},
{'name': 'Tommy', 'age': 43, 'brother': 'Joel'},
{'name': 'Ellie', 'age': 14, 'brother': None}]

所需的 output:

[{'name': 'Joel', 'age': 48, 'brother': 'Tommy'},
{'name': 'Ellie', 'age': 14, 'brother': None}]

您可以尝试以下代码,这可能对您有所帮助:

[value for value in list_of_dicts if value.get('name') in ['Joel', 'Ellie']]

所以你的代码将是:

dict1 = {'name': 'Joel', 'age': 48, 'brother': 'Tommy'}
dict2 = {'name': 'Tommy', 'age': 43, 'brother': 'Joel'}
dict3 = {'name': 'Ellie', 'age': 14, 'brother': None}

list_of_dicts = [dict1, dict2, dict3]
final_list = [value for value in list_of_dicts if value.get('name') in ['Joel', 'Ellie']]
print(final_list)

暂无
暂无

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

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