Remove duplicate dict in list in Python

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

    Here's a quick one-line solution with a doubly-nested list comprehension (based on @Emmanuel 's solution).

    This uses a single key (for example, a) in each dict as the primary key, rather than checking if the entire dict matches

    [i for n, i in enumerate(list_of_dicts) if i.get(primary_key) not in [y.get(primary_key) for y in list_of_dicts[n + 1:]]]
    

    It's not what OP asked for, but it's what brought me to this thread, so I figured I'd post the solution I ended up with

提交回复
热议问题