假设我有一个字典列表:

[
    {'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},
]

当前回答

可能有更优雅的解决方案,但我认为最好添加一个更详细的解决方案,使其更容易遵循。这里假设没有唯一键,你有一个简单的k,v结构,并且你使用的python版本保证了列表顺序。这适用于原来的职位。

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

# list of keys
keys = [k for k in data_set[0]]

# Create a List of Lists of the values from the data Set
data_set_list = [[v for v in v.values()] for v in data_set]

# Dedupe
new_data_set = []
for lst in data_set_list:
    # Check if list exists in new data set
    if lst in new_data_set:
        print(lst)
        continue
    # Add list to new data set
    new_data_set.append(lst)

# Create dicts
new_data_set = [dict(zip(keys,lst)) for lst in new_data_set]    

print(new_data_set)

其他回答

我不知道你是否只希望列表中dicts的id是唯一的,但如果目标是有一组dict,其中所有键的值都是唯一的。你应该像这样使用元组键:

>>> L=[
...     {'id':1,'name':'john', 'age':34},
...    {'id':1,'name':'john', 'age':34}, 
...    {'id':2,'name':'hanna', 'age':30},
...    {'id':2,'name':'hanna', 'age':50}
...    ]
>>> len(L)
4
>>> L=list({(v['id'], v['age'], v['name']):v for v in L}.values())
>>>L
[{'id': 1, 'name': 'john', 'age': 34}, {'id': 2, 'name': 'hanna', 'age': 30}, {'id': 2, 'name': 'hanna', 'age': 50}]
>>>len(L)
3

希望它能帮助你或其他有顾虑的人....

你可以使用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)))

在python 3中,简单的技巧,但基于唯一字段(id):

data = [ {'id': 1}, {'id': 1}]

list({ item['id'] : item for item in data}.values())

让我加上我的。

对目标字典进行排序,使{'a': 1, 'b': 2}和{'b': 2, 'a': 1}不会被区别对待 将其设置为json格式 通过set重复数据删除(因为set不适用于字典) 同样,通过json.loads将其转换为dict

import json

[json.loads(i) for i in set([json.dumps(i) for i in [dict(sorted(i.items())) for i in target_dict]])]
a = [
{'id':1,'name':'john', 'age':34},
{'id':1,'name':'john', 'age':34},
{'id':2,'name':'hanna', 'age':30},
]

b = {x['id']:x for x in a}.values()

print(b)

输出:

[{“年龄”:34岁“id”:1、“名称”:“约翰”},{“id”:“年龄”:30日2时,“名字”:“汉娜”}]