【问题标题】:Delete duplicate dictionary form a list of dictionaries从字典列表中删除重复的字典
【发布时间】:2022-11-27 08:54:54
【问题描述】:

我想从字典列表中找到重复的目录并删除其中一个,但它会产生错误。姓名、年龄、组只有所有 3 个应该是相同的值才能将其作为重复字典

a = [
  {"name": "Tom", "age": 21,"group":"sdd","points":0},
  {"name": "Mark", "age": 5,"group":"sdo","points":0},
  {"name": "Pam", "age": 7,"group":"spp","points":0},
  {"name": "Tom", "age": 21,"group":"sdd","points":0},
  {"name": "Buke", "age": 31,"group":"pool","points":0}
]

print(a)
for i in range(len(a)):
  for j in range(i+1,len(a)):
    if a[i] == a[j]:
      a.pop[j]
      

print(a)

【问题讨论】:

  • 需要明确的是,您不关心 "points" 的值是否相同?

标签: python list dictionary


【解决方案1】:

您可以将每个 dict 转换为 tuple,然后应用 set 删除重复项。最后回到dicts 的list

a = [
  {"name": "Tom", "age": 21,"group":"sdd","points":0},
  {"name": "Mark", "age": 5,"group":"sdo","points":0},
  {"name": "Pam", "age": 7,"group":"spp","points":0},
  {"name": "Tom", "age": 21,"group":"sdd","points":0},
  {"name": "Buke", "age": 31,"group":"pool","points":0}
]

a_new = list(map(dict, set(tuple(dct.items()) for dct in a)))
print(a_new)

输出:

[{'name': 'Mark', 'age': 5, 'group': 'sdo', 'points': 0},
 {'name': 'Tom', 'age': 21, 'group': 'sdd', 'points': 0},
 {'name': 'Buke', 'age': 31, 'group': 'pool', 'points': 0},
 {'name': 'Pam', 'age': 7, 'group': 'spp', 'points': 0}]

【讨论】:

    【解决方案2】:

    如果我理解正确的话,只有当姓名、年龄和组匹配时才会重复:

    a = [
        {"name": "Tom", "age": 21, "group": "sdd", "points": 0},
        {"name": "Mark", "age": 5, "group": "sdo", "points": 0},
        {"name": "Pam", "age": 7, "group": "spp", "points": 0},
        {"name": "Tom", "age": 21, "group": "sdd", "points": 0},
        {"name": "Buke", "age": 31, "group": "pool", "points": 0},
    ]
    
    out, seen = [], set()
    for d in a:
        tpl = d["name"], d["age"], d["group"]
        if tpl not in seen:
            seen.add(tpl)
            out.append(d)
    
    print(out)
    

    印刷:

    [
        {"name": "Tom", "age": 21, "group": "sdd", "points": 0},
        {"name": "Mark", "age": 5, "group": "sdo", "points": 0},
        {"name": "Pam", "age": 7, "group": "spp", "points": 0},
        {"name": "Buke", "age": 31, "group": "pool", "points": 0},
    ]
    

    【讨论】:

      猜你喜欢
      • 2019-09-26
      • 1970-01-01
      • 2020-07-14
      • 2019-01-09
      • 2012-02-16
      • 1970-01-01
      • 2011-10-28
      • 2018-04-14
      相关资源
      最近更新 更多