如何在列表中快速找到重复的词典?

时间:2017-06-26 11:47:01

标签: python list dictionary

我有一个词典列表,例如:

list_of_clients = [
    {"Name": "Alex", "Surname": "Dorfman", ...},
    {"Name": "Serge", "Surname": "Ioffe"}, ...
]

我知道同一个客户端的列表中有重复的词典。

有没有办法快速打印出来?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以保留set已见过的名字。您必须定义应考虑哪些密钥。在这种情况下:["Name", "Surname"]。如果您愿意,只需添加更多:

list_of_clients = [{"Name": "Alex", "Surname": "Dorfman"}, {"Name": "Serge", "Surname": "Ioffe"}, {"Name": "Alex", "Surname": "Dorfman"}, {"Name": "Serge", "Surname": "Ioffe"}]

already_seen = set()

for client in list_of_clients:
    complete_name = tuple(client.get(k) for k in ["Name", "Surname"])
    if complete_name in already_seen:
        print("Duplicate : %s" % (complete_name,))
    already_seen.add(complete_name)

输出:

Duplicate : ('Alex', 'Dorfman')
Duplicate : ('Serge', 'Ioffe')

答案 1 :(得分:0)

您可以尝试:

res = set(tuple(client.items() 
                for client in list_of_clients 
                if list_of_clients.count(client) > 1))

set()将删除结果中的重复项,并且tuple()是必需的(至少在Python3中),因为items()本身仍然不可清除。

正如其他人所说,这不会使项目保持有序,但如果您只想删除重复项,这就足够了。