如果值在项目中重复,如何从字典列表中删除字典

How to remove dictionary from list of dictionary if value repeats in items

词典列表如下

l = [
{'firstname': 'joe', 'surname': 'ABCD', 'tile' : 'DE'},
{'firstname': 'john', 'surname': 'DEF', 'tile' : 'BC'},
{'firstname': 'joe', 'surname': 'bloggs', 'tile' : 'DE'},
{'firstname': 'jane', 'surname': 'HH', 'tile' : 'AD'}
]

如果 firstnametile 匹配

,则需要从 l 中删除项目

伪代码

for i in l:
   if i['firstname'] + i['tile'] in l:
        l.pop(i)
       

我已经过了python remove duplicate dictionaries from a list

它删除了整个字典匹配项

也通过了第二个答案python remove duplicate dictionaries from a list

试试这个,

扩展了这个 SO 答案 Index of duplicates items in a python list

代码:

from collections import defaultdict

l = [
{'firstname': 'joe', 'surname': 'ABCD', 'tile' : 'DE'},
{'firstname': 'john', 'surname': 'DEF', 'tile' : 'BC'},
{'firstname': 'joe', 'surname': 'bloggs', 'tile' : 'DE'},
{'firstname': 'jane', 'surname': 'HH', 'tile' : 'AD'}
]


group = [(item['firstname'], item['tile']) for item in l]

def list_duplicates(seq):
    tally = defaultdict(list)
    for i,item in enumerate(seq):
        tally[item].append(i)
    return ((key,locs) for key,locs in tally.items() 
                            if len(locs)>=1)

new_l = []
for dup in list_duplicates(group):
    new_l.append(l[dup[1][0]])
  
new_l

输出:

[{'firstname': 'joe', 'surname': 'ABCD', 'tile': 'DE'},
 {'firstname': 'john', 'surname': 'DEF', 'tile': 'BC'},
 {'firstname': 'jane', 'surname': 'HH', 'tile': 'AD'}]

尝试:

l = [
    {"firstname": "joe", "surname": "ABCD", "tile": "DE"},
    {"firstname": "john", "surname": "DEF", "tile": "BC"},
    {"firstname": "joe", "surname": "bloggs", "tile": "DE"},
    {"firstname": "jane", "surname": "HH", "tile": "AD"},
]

out = {}
for d in reversed(l):
    out[(d["firstname"], d["tile"])] = d

print(list(out.values()))

打印:

[
    {"firstname": "jane", "surname": "HH", "tile": "AD"},
    {"firstname": "joe", "surname": "ABCD", "tile": "DE"},
    {"firstname": "john", "surname": "DEF", "tile": "BC"},
]