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 ?
CodePudding user response:
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)]
CodePudding user response:
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}
CodePudding user response:
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)]