[英]How to remove dictionary from list of dictionary if value repeats in items
List of dictionary is below字典列表如下
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'}
]
Need to delete item from l
if firstname
and tile
matches如果
firstname
和tile
匹配,需要从l
中删除项目
pseudo code伪代码
for i in l:
if i['firstname'] + i['tile'] in l:
l.pop(i)
I have gone through python remove duplicate dictionaries from a list我已经通过python 从列表中删除重复的字典
its removing entire dict matches它删除整个字典匹配
Also gone through second answer python remove duplicate dictionaries from a list还经历了第二个答案python 从列表中删除重复的字典
Try:尝试:
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()))
Prints:印刷:
[
{"firstname": "jane", "surname": "HH", "tile": "AD"},
{"firstname": "joe", "surname": "ABCD", "tile": "DE"},
{"firstname": "john", "surname": "DEF", "tile": "BC"},
]
Try this,尝试这个,
Extended this SO answer Index of duplicates items in a python list扩展了这个 SO answer Index of duplicates items in a python list
Code:代码:
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
Output:输出:
[{'firstname': 'joe', 'surname': 'ABCD', 'tile': 'DE'},
{'firstname': 'john', 'surname': 'DEF', 'tile': 'BC'},
{'firstname': 'jane', 'surname': 'HH', 'tile': 'AD'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.