4

Possible Duplicate:
how to uniqify a list of dict in python

I have a list as follows

[
{'x':'1','y':'1'},{'x':'2','y':'2'},{'x':'1','y':'1'}
]

I want to get a new list as follows (unique elements)

[
{'x':'1','y':'1'},{'x':'2','y':'2'}
]

What's the best way?

Community
  • 1
  • 1
Jisson
  • 3,566
  • 8
  • 38
  • 71
  • Are the two identical dicts in the example different objects (i.e., two objects with distinct ids)? If so, the problem is more complex, since methods of making a unique list such as casting to a set, etc. will not work. – Andrew Gorcester Jul 31 '12 at 14:02
  • Thanks @DSM , your suggesion works fine – Jisson Jul 31 '12 at 14:13

2 Answers2

5
import ast

l = [
{'x':'1','y':'1'},{'x':'2','y':'2'},{'x':'1','y':'1'}
]

[ast.literal_eval(el1) for el1 in set([str(el2) for el2 in l])]

Usually an easy solution for keeping unique elements is to add them to a set. However, since a dict is unhashable (can't be put in a set), I provided a workaround. First, the dicts are converted to strings, placed in a set (to keep the unique ones), and then converted back to dicts using ast.literal_eval.

Lanaru
  • 9,421
  • 7
  • 38
  • 64
4
>>> lst = [{'x':'1','y':'1'},{'x':'2','y':'2'},{'x':'1','y':'1'}]
>>> map(dict, set(tuple(x.items()) for x in lst))
[{'y': '1', 'x': '1'}, {'y': '2', 'x': '2'}]
>>> 
applicative_functor
  • 4,926
  • 2
  • 23
  • 34