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

Question:

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:

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

What is the easiest way to achieve this ?

Asked By: Bluemarble

||

Answers:

tmp = dict((y, x) for x, y in touple)

my_dict = dict()
for val, key in tmp.items():
    if key not in my_dict.keys():
        my_dict[key] = val
    else:
        if my_dict[key] < val:
            my_dict[key] = val

Output: my_dict

 {'Northwest Airlines': 93, 'Southwest Airlines': 79, 'NorthWestern': 77}
Answered By: Will
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)]
Answered By: Marcus.Aurelianus

If you don’t mind the order of the result. You can use sort, itertools.groupby, and max to avoid using loop.

[ max(v) for _, v in itertools.groupby(sorted(touple), key=lambda t: t[0]) ]

# [('NorthWestern', 77), ('Northwest Airlines', 93), ('Southwest Airlines', 79)]
Answered By: ILS
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.