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
CodePudding user response:
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"},
]
CodePudding user response:
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'}]