'Remove duplicates with low score in list of dicts

I currently have the following list of dicts:

[
    {'id': '1', 'sim': 0.81},
    {'id': '1', 'sim': 0.72},
    {'id': '2', 'sim': 0.85},    
    {'id': '2', 'sim': 0.81},
    {'id': '2', 'sim': 0.72}
]

I'd like to remove the duplicates which have not the highest sim and get the following:

[
    {'id': '1', 'sim': 0.81},
    {'id': '2', 'sim': 0.85},
]


Solution 1:[1]

sims_list = [
    {'id': '1', 'sim': 0.81},
    {'id': '1', 'sim': 0.72},
    {'id': '2', 'sim': 0.85},
    {'id': '2', 'sim': 0.81},
    {'id': '2', 'sim': 0.72}
]

result = []
for each_sim in sims_list:
    for each_result in result:
        if each_result["id"] == each_sim["id"]:
            each_result["sim"] = max(each_result["sim"], each_sim["sim"])
            break
    else:
        result.append(each_sim)

print(result)

Output

[{'id': '1', 'sim': 0.81}, {'id': '2', 'sim': 0.85}]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saleel Ahsan