I have below list:
lst = [
{'name': 'bezel', 'conf': 0.67},
{'name': 'plate', 'conf': 0.69},
{'name': 'bezel', 'conf': 0.65},
{'name': 'plate', 'conf': 0.46},
{'name': 'bezel', 'conf': 0.42}
]
Above list contains duplicate dicts which has name as bezel and plate. There can be n number of names in the list. I want to remove these duplicate dicts and only keep the dict which has high conf. So the output would look like below:
lst = [
{'name': 'bezel', 'conf': 0.67},
{'name': 'plate', 'conf': 0.69}
]
I can use multiple for and if loops to get the output but is there any easier way of doing this? Thanks
Below is what I have done so far
newLst = [] # creating new list to save data
for item in lst:
if any(d['name'] == item['name'] for d in newLst): # Checking if current item exist in newLst
idx = next((index for (index, d) in enumerate(newLst) if d["name"] == item['name']), None) # Get the index of current item name from newLst
if newLst[idx]['conf'] < item['conf']: # Check if its greater conf
del newLst[idx]
newLst.append({'name': item['name'], 'conf': item['conf']})
else:
newLst.append({'name': item['name'], 'conf': item['conf']}) # If not add current item
print(newLst)