Remove duplicate dict in list in Python

前端 未结 12 1012
太阳男子
太阳男子 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

    If you want to preserve the Order, then you can do

    from collections import OrderedDict
    print OrderedDict((frozenset(item.items()),item) for item in data).values()
    # [{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}]
    

    If the order doesn't matter, then you can do

    print {frozenset(item.items()):item for item in data}.values()
    # [{'a': 3222, 'b': 1234}, {'a': 123, 'b': 1234}]
    

提交回复
热议问题