ramesh.c - 1 year ago 68

Python Question

I have a list:

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

`{'x':1, 'y':2}`

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

`list(set(d))`

Answer Source

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