ramesh.c ramesh.c - 4 months ago 12
Python Question

how to uniqify a list of dict in python

I have a list:

d = [{'x':1, 'y':2}, {'x':3, 'y':4}, {'x':1, 'y':2}]


{'x':1, 'y':2}
comes more than once I want to remove it from the list.My result should be:

d = [{'x':1, 'y':2}, {'x':3, 'y':4} ]


Note:
list(set(d))
is not working here throwing an error.

GWW GWW
Answer

If your value is hashable this will work:

>>> [dict(y) for y in set(tuple(x.items()) for x in d)]
[{'y': 4, 'x': 3}, {'y': 2, 'x': 1}]

EDIT:

I tried it with no duplicates and it seemed to work fine

>>> d = [{'x':1, 'y':2}, {'x':3, 'y':4}]
>>> [dict(y) for y in set(tuple(x.items()) for x in d)]
[{'y': 4, 'x': 3}, {'y': 2, 'x': 1}]

and

>>> d = [{'x':1,'y':2}]
>>> [dict(y) for y in set(tuple(x.items()) for x in d)]
[{'y': 2, 'x': 1}]
Comments