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)

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

Leave a Reply