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

How to filter out dictionaries with the same value for a certain key from a list?

I have the following list of objects:

l = [{'name': 'Mike', 'age': 31},
     {'name': 'Peter', 'age': 29},
     {'name': 'Mike', 'age': 44}]

I want to filter it based on the name, and because "Mike" is a duplicate in this case, I want to remove all entries with name=Mike (regardless of the age).

(i.e. to get the same list but without the entries that have name=Mike)

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

What’s the best approach to do that?

>Solution :

You can use a Counter to get the counts of all names. Then filter the names that appear more than once:

from collections import Counter

l = [{'name': 'Mike', 'age': 31},
     {'name': 'Peter', 'age': 29},
     {'name': 'Mike', 'age': 44}]

names_count = Counter(d['name'] for d in l)
new_l = list(filter(lambda d: names_count[d['name']] == 1, l))
print(new_l)

Will give:

[{'name': 'Peter', 'age': 29}]
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