假设我有一个字典列表:

[
    {'id': 1, 'name': 'john', 'age': 34},
    {'id': 1, 'name': 'john', 'age': 34},
    {'id': 2, 'name': 'hanna', 'age': 30},
]

如何获得唯一字典的列表(删除重复项)?

[
    {'id': 1, 'name': 'john', 'age': 34},
    {'id': 2, 'name': 'hanna', 'age': 30},
]

当前回答

这里有一个内存开销很小的实现,代价是不像其他实现那样紧凑。

values = [ {'id':2,'name':'hanna', 'age':30},
           {'id':1,'name':'john', 'age':34},
           {'id':1,'name':'john', 'age':34},
           {'id':2,'name':'hanna', 'age':30},
           {'id':1,'name':'john', 'age':34},]
count = {}
index = 0
while index < len(values):
    if values[index]['id'] in count:
        del values[index]
    else:
        count[values[index]['id']] = 1
        index += 1

输出:

[{'age': 30, 'id': 2, 'name': 'hanna'}, {'age': 34, 'id': 1, 'name': 'john'}]

其他回答

由于id足以检测重复项,且id是可哈希的:在以id为键的字典中运行它们。每个键的值都是原始字典。

deduped_dicts = dict((item["id"], item) for item in list_of_dicts).values()

在Python 3中,values()不返回列表;你需要在list()中包装整个表达式的右边,并且你可以将表达式的部分更经济地写成dict理解:

deduped_dicts = list({item["id"]: item for item in list_of_dicts}.values())

注意,结果可能与原始结果的顺序不同。如果这是一个要求,您可以使用集合。OrderedDict而不是dict。

顺便说一句,将数据保存在使用id作为键的字典中可能很有意义。

你可以使用numpy库(适用于Python2。x只):

   import numpy as np 

   list_of_unique_dicts=list(np.unique(np.array(list_of_dicts)))

让它在Python 3中工作。X(以及numpy的最新版本),您需要将字典数组转换为numpy字符串数组,例如。

list_of_unique_dicts=list(np.unique(np.array(list_of_dicts).astype(str)))

这里提到的所有答案都很好,但在一些答案中,如果字典项有嵌套的列表或字典,就会面临错误,所以我建议简单的答案

a = [str(i) for i in a]
a = list(set(a))
a = [eval(i) for i in a]

这里有很多答案,所以让我再补充一个:

import json
from typing import List

def dedup_dicts(items: List[dict]):
    dedupped = [ json.loads(i) for i in set(json.dumps(item, sort_keys=True) for item in items)]
    return dedupped

items = [
    {'id': 1, 'name': 'john', 'age': 34},
    {'id': 1, 'name': 'john', 'age': 34},
    {'id': 2, 'name': 'hanna', 'age': 30},
]
dedup_dicts(items)

如果字典仅由所有项唯一标识(ID不可用),则可以使用JSON来使用答案。下面是一个不使用JSON的替代方法,只要所有字典值都是不可变的,它就可以工作

[dict(s) for s in set(frozenset(d.items()) for d in L)]