Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One way to go would be to use pandas :

import pandas as pd

d = [
    {'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}
]

df = pd.DataFrame(d)

df = df.groupby(['id'], sort=False)['sim'].max()

Then you can keep using it as a Dataframe, or going back to nested dictionnaries depending on what you need.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading