How to delete duplicated dictionary objects from a List of dictionaries

  • A+
Category:Languages

I want to delete duplicated dictionary objects from a List of dictionaries. I don't want the dict element that has the same 'plate' element with another dict element in the list. I want it only once.

datalist = [  {     'plate': "01",     'confidence' : "80" },  {     'plate': "01",     'confidence' : "60" },  {     'plate': "02",     'confidence' : "91" },  {     'plate': "02",     'confidence' : "91" }, ] 

My output should be like this:

datalist = [  {     'plate': "01",     'confidence' : "80" },  {     'plate': "02",     'confidence' : "91" }, ] 

This is my code, but I'm not getting the exact result.

def filter(datalist):     previous = ""     for data in datalist:         current  = data['plate']         if current is previous:             datalist.remove(data)         previous = current       return datalist  datalist = [      {         'plate': "01",         'confidence' : "80"     },      {         'plate': "01",         'confidence' : "60"     },      {         'plate': "02",         'confidence' : "91"     },      {         'plate': "02",         'confidence' : "91"     }, ]   print (filter(datalist)) 

This gives me the output:

[      {         'plate': "01",         'confidence' : "80"     },      {         'plate': "02",         'confidence' : "91"     },      {         'plate': "02",         'confidence' : "91"     }, ] 

which is not expected, what's wrong with my code.

 


If any element from the groups of duplicates is acceptable, you could do:

datalist = [     {'plate': "01", 'confidence': "80"},     {'plate': "01", 'confidence': "60"},     {'plate': "02", 'confidence': "91"},     {'plate': "02", 'confidence': "91"}, ]  result = list({ d['plate'] : d for d in datalist }.values()) print(result) 

Output

[{'plate': '02', 'confidence': '91'}, {'plate': '01', 'confidence': '60'}] 

The idea is to create a dictionary where the keys are values of plate and the values are the dictionaries themselves. If you want to keep the first duplicate entries use reversed:

result = list({d['plate']: d for d in reversed(datalist)}.values()) 

Output

[{'plate': '02', 'confidence': '91'}, {'plate': '01', 'confidence': '80'}] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: