Remove duplicate dict in list in Python

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

    Another one-liner based on list comprehensions:

    >>> d = [{'a': 123}, {'b': 123}, {'a': 123}]
    >>> [i for n, i in enumerate(d) if i not in d[n + 1:]]
    [{'b': 123}, {'a': 123}]
    

    Here since we can use dict comparison, we only keep the elements that are not in the rest of the initial list (this notion is only accessible through the index n, hence the use of enumerate).

提交回复
热议问题