如果第一个键的值匹配,则从字典列表中删除这两个项目

时间:2021-03-02 18:40:32

标签: python list dictionary duplicates

details = [
{"id": "1", "name": "Bob", "age": 21, "student" : "yes"},
{"id": "1", "name": "Mary", "age": 25, "student" : "yes"},
{"id": "2", "name": "Jeff", "age": 22, "student" : "no"}
]

预期:

[{"id": "2", "name": "Jeff", "age": 22, "student" : "no"}]

我尝试了删除重复项的解决方案,但在这些方法中 id=1 和 2 仍然是唯一值,但是如果重复 id,我需要删除两个或多个匹配对及其字典,只留下一个不重复。请提供任何帮助。

2 个答案:

答案 0 :(得分:3)

您可以保留一个 list 来检查 id 的多次出现,然后您可以忽略该条目

details = [
{"id": "1", "name": "Bob", "age": 21, "student" : "yes"},
{"id": "1", "name": "Mary", "age": 25, "student" : "yes"},
{"id": "2", "name": "Jeff", "age": 22, "student" : "no"}
]

ids = []
to_be_deleted = []

for i in details:
    if i['id'] in ids:
        to_be_deleted.append(i['id'])
    else:
        ids.append(i['id'])

output = [i for i in details if i['id'] not in to_be_deleted]

print(output)
[{'id': '2', 'name': 'Jeff', 'age': 22, 'student': 'no'}]

答案 1 :(得分:0)

使用 collections.Counterids 只出现一次。

from collections import Counter

details = [
{"id": "1", "name": "Bob", "age": 21, "student" : "yes"},
{"id": "1", "name": "Mary", "age": 25, "student" : "yes"},
{"id": "2", "name": "Jeff", "age": 22, "student" : "no"}
]

c = Counter(map(lambda x: x['id'], details))

details = list(filter(lambda x: c[x['id']] == 1, details))

print(details)

打印:

[{'id': '2', 'name': 'Jeff', 'age': 22, 'student': 'no'}]