使用 deepcopy 从 Python 中的字典列表中删除重复项

Removing duplicates from a list of dictionaries in Python using deepcopy

我有一个词典列表:

list_1 = [{'account': '1234', 'email' : 'abc@xyz.com'}, ... , ...]

我想删除列表中包含重复电子邮件的条目。

import copy
list_2 = copy.deepcopy(list_1)
for i in mainList
 for j in range(len(list_2)-1, -1, -1):
   if ((list_2[j]["email"] == mainList[i])):
                    list_1.remove(list1[j])

mainList 这是我正在比较值的电子邮件列表。 mainList 看起来像这样:

['abc@xyz.com', 'efg@cvb.com, ..., ...]

主要问题是 list_1 输出不正确。如果我使用列表、切片甚至列表理解来复制它,它会变成空的。 最终结果应该是 list_1,每封邮件只包含一个 element/list/dictionary。 使用 copy 或 deepcopy 至少给了我一些东西。似乎有时我也会遇到索引错误。 使用 for x in list_2: 而不是 returns list_1 只有一项。 我得到的最接近正确答案的是在删除项目时迭代 list_1 本身,但它不是 100% 正确。

遍历您的词典列表,并仅在新词典不存在时才将每封电子邮件保存在新词典中。

temp = dict()
list_1 = [{'account': '1234', 'email': 'abc@xyz.com'}]
for d in list_1:
    if d['email'] in temp:
        continue
    else:
        temp[d['email']] = d
final_list = list(temp.values())

您似乎想删除重复的词典。请在问题中也提及重复的词典。

di = [{'account': '1234', 'email' : 'abc@xyz.com'}, {'account1': '12345', 
'email1' : 'abcd@xyz.com'}, {'account': '1234', 'email' : 'abc@xyz.com'}]
s=[i for n, i in enumerate(d) if i not in di[n + 1:]]
Print(s)

这将为您提供所需的输出

[{'account1': '12345', 'email1': 'abcd@xyz.com'}, {'account': '1234', 'email': 
'abc@xyz.com'}]

我认为完成此操作的最简单方法是根据您的密钥创建 list_1(字典)的索引版本。

list_1 = [
    {'account': '1234', 'email' : 'abc@xyz.com'},
    {'account': '1234', 'email' : 'abc@xyz.com'},
    {'account': '4321', 'email' : 'zzz@xyz.com'},
]

list_1_indexed = {}
for row in list_1:
    list_1_indexed.setdefault(row['email'], row)
list_2 = list(list_1_indexed.values())

print(list_2)

这会给你:

[
    {'account': '1234', 'email': 'abc@xyz.com'},
    {'account': '4321', 'email': 'zzz@xyz.com'}
]

我不确定我是否会推荐它,但如果您想使用推导式,您可以这样做:

list_2 = list({row['email']: row for row in list_1}.values())

请注意,第一个策略导致第一个关键行获胜,理解最后一个关键行获胜。