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 ?
>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)]