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

Python Touples – Keep only the largest value if First item is found duplicate

I have a python list of touples like this:

touple = [('Northwest Airlines', 93), 
         ('Northwest Airlines', 81), 
         ('Southwest Airlines', 79), 
         ('NorthWestern', 77), 
         ('NorthWestern', 69), 
         ('Southwest Airlines', 69)]

Several of these items are duplicate. I want to keep only unique Touples having the largest value as the 2nd item.

The output I want to achieve is like this:

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

processed_touple = [('Northwest Airlines', 93),                      
                   ('Southwest Airlines', 79), 
                   ('NorthWestern', 77)]

What is the easiest way to achieve this ?

>Solution :

dic = {}

for item in touple:
    name, score = item
    if name not in dic:
        dic[name] = score
    else:
        if score > dic[name]:
            dic[name] = score
        

print(list(dic.items()))

output:

[('Northwest Airlines', 93), ('Southwest Airlines', 79), ('NorthWestern', 77)]
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