Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 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}]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading