[英]Filter key-values from a list of dictionaries
I have a list of dictionaries and I need to filter that list where a certain key has a certain value.我有一个字典列表,我需要过滤某个键具有特定值的列表。 For example, only
dict
s where 'name'
is 'Joel'
or 'Ellie'
.例如,只有
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}]
Desired output:所需的 output:
[{'name': 'Joel', 'age': 48, 'brother': 'Tommy'},
{'name': 'Ellie', 'age': 14, 'brother': None}]
You can try the below code, this might help you:您可以尝试以下代码,这可能对您有所帮助:
[value for value in list_of_dicts if value.get('name') in ['Joel', 'Ellie']]
So your code will be:所以你的代码将是:
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.