从字典列表中删除重复项python

sha*_*nky 4 python

我正在尝试从以下列表中删除重复项

 distinct_cur = [{'rtc': 0, 'vf': 0, 'mtc': 0, 'doc': 'good job', 'foc': 195, 'st': 0.0, 'htc': 2, '_id': ObjectId('58e86a550a0aeff4e14ca6bb'), 'ftc': 0}, 
 {'rtc': 0, 'vf': 0, 'mtc': 0, 'doc': 'good job', 'foc': 454, 'st': 0.8, 'htc': 1, '_id': ObjectId('58e8d03958ae6d179c2b4413'), 'ftc': 1},
 {'rtc': 0, 'vf': 2, 'mtc': 1, 'doc': 'test', 'foc': 45, 'st': 0.8, 'htc': 12, '_id': ObjectId('58e8d03958ae6d180c2b4446'), 'ftc': 0}] 
Run Code Online (Sandbox Code Playgroud)

基于以下条件的字典:如果'doc'键值文本相同,则应删除其中一个字典。我尝试了以下解决方案

distinct_cur = [dict(y) for y in set(tuple(x.items()) for x in cur)] 
Run Code Online (Sandbox Code Playgroud)

但最终列表中仍存在重复项。

以下是所需的输出,如键“ doc”值的第一个和第二个distinct_cur文本相同(很好):

[{'rtc': 0, 'vf': 0, 'mtc': 0, 'doc': 'good job', 'foc': 195, 'st': 0.0, 'htc': 2, '_id': ObjectId('58e86a550a0aeff4e14ca6bb'), 'ftc': 0}, 
 {'rtc': 0, 'vf': 2, 'mtc': 1, 'doc': 'test', 'foc': 45, 'st': 0.8, 'htc': 12, '_id': ObjectId('58e8d03958ae6d180c2b4446'), 'ftc': 0}] 
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Jea*_*bre 6

您正在创建一个set由不同元素构成的对象,并期望它将根据您唯一知道的标准来删除重复项。

您必须遍历列表,仅当doc其值与先前值不同时才将其添加到结果列表中:例如:

done = set()
result = []
for d in distinct_cur:
    if d['doc'] not in done:
        done.add(d['doc'])  # note it down for further iterations
        result.append(d)
Run Code Online (Sandbox Code Playgroud)

doc通过将已知键注册在辅助集中,将仅保留具有相同键的字典的第一个匹配项。

另一种可能性是使用带有键的字典作为字典的键"doc",并在列表中向后迭代,以便第一项覆盖列表中的最后一项:

result = {i['doc']:i for i in reversed(distinct_cur)}.values()
Run Code Online (Sandbox Code Playgroud)


sma*_*sey 5

我看到两个类似的解决方案,具体取决于您的域问题:您想要保留密钥的第一个实例还是最后一个实例?

使用最后一个(以便覆盖以前的匹配)更简单:

d = {r['doc']: r for r in distinct_cur}.values()
Run Code Online (Sandbox Code Playgroud)