Remove duplicate dict in list in Python

前端 未结 12 916
太阳男子
太阳男子 2020-11-22 09:10

I have a list of dicts, and I\'d like to remove the dicts with identical key and value pairs.

For this list: [{\'a\': 123}, {\'b\': 123}, {\'a\': 123}]<

12条回答
  •  無奈伤痛
    2020-11-22 09:48

    You can use a set, but you need to turn the dicts into a hashable type.

    seq = [{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}, {'a': 123, 'b': 1234}]
    unique = set()
    for d in seq:
        t = tuple(d.iteritems())
        unique.add(t)
    

    Unique now equals

    set([(('a', 3222), ('b', 1234)), (('a', 123), ('b', 1234))])
    

    To get dicts back:

    [dict(x) for x in unique]
    

提交回复
热议问题