简体   繁体   中英

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' .

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:

[{'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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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