簡體   English   中英

如果項目中的值重復,如何從字典列表中刪除字典

[英]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 從列表中刪除重復的字典

它刪除整個字典匹配

還經歷了第二個答案python 從列表中刪除重復的字典

嘗試:

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"},
]

嘗試這個,

擴展了這個 SO answer 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'}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM