how to uniqify a list of dict in python

后端 未结 6 1876
长发绾君心
长发绾君心 2020-12-10 01:10

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

6条回答
  •  孤街浪徒
    2020-12-10 01:33

    Dicts aren't hashable, so you can't put them in a set. A relatively efficient approach would be turning the (key, value) pairs into a tuple and hashing those tuples (feel free to eliminate the intermediate variables):

    tuples = tuple(set(d.iteritems()) for d in dicts)
    unique = set(tuples)
    return [dict(pairs) for pairs in unique]
    

    If the values aren't always hashable, this is not possible at all using sets and you'll propably have to use the O(n^2) approach using an in check per element.

提交回复
热议问题