Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python remove duplicate dictionaries from a list [duplicate]

Tags:

python

I have a list of dictionaries

l = [ {'firstname': 'joe', 'surname': 'bloggs'}, {'firstname': 'john', 'surname': 'smith'}, {'firstname': 'joe', 'surname': 'bloggs'}, {'firstname': 'jane', 'surname': 'bloggs'} ] 

how do i remove duplicates i.e. {'firstname': 'joe', 'surname': 'bloggs'} appears twice so would want it only appearing once?

like image 991
John Avatar asked Aug 17 '11 09:08

John


People also ask

How do I remove duplicates from a dictionary list?

Since the tuples can be hashed, you can remove duplicates using set (using a set comprehension here, older python alternative would be set(tuple(d. items()) for d in l) ) and, after that, re-create the dictionaries from tuples with dict . where: l is the original list.

Do dictionaries remove duplicates?

dict. fromkeys() is a built-in function that generates a dictionary from the keys you have specified. Because dictionaries cannot include duplicate keys, the function will remove any duplicate values from our list.

How do you eliminate duplicates in Python?

Use DataFrame. drop_duplicates() to Drop Duplicate and Keep First Rows. You can use DataFrame. drop_duplicates() without any arguments to drop rows with the same values on all columns.


1 Answers

Something like this should do the stuff :

result = [dict(tupleized) for tupleized in set(tuple(item.items()) for item in l)] 

first, I transform the inital dict in a list of tuples, then I put them into a set (that removes duplicates entries), and then back into a dict.

like image 60
Cédric Julien Avatar answered Sep 18 '22 10:09

Cédric Julien