Home > Net >  Filter key-values from a list of dictionaries
Filter key-values from a list of dictionaries

Time:03-22

I have a list of dictionaries and I need to filter that list where a certain key has a certain value. For example, only dicts 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}]

CodePudding user response:

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)
  • Related