简体   繁体   中英

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

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

its removing entire dict matches

Also gone through second answer python remove duplicate dictionaries from a list

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

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'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM