I have the following list containing tuples that have to values:
mylist=[(3, 'a'), (2, 'b'), (4, 'a'), (5, 'c'), (2, 'a'), (1, 'b')]
Is there a way to sum all values that share the same name? Something like:
(9, 'a'), (3, 'b'), (5, 'c')
I tried iterating tuples with for loop but can't get what i want.
Thank you
You can use
itertools.groupby
(after sorting by the second value of each tuple) to create groups. Then for each group, sum the first element in each tuple, then create a tuple per group in a list comprehension.A simple approach without any dependencies:
Use a dict (or defaultdict) to aggregate over your tuples:
You can create a
dict
which has sum of individual keys.