Python | Grouped summation of tuple list
Many times, we are given a list of tuples and we need to group its keys and perform certain operation while grouping. The most common operation being addition. Let’s discuss certain ways in which this task can be performed. Apart from addition other operations can also be performed by doing small changes.
Method : Using
This task can be performed using the Counter function as it internally groups and addition operator can be used to specify the functionality on the grouped result.
The original list 1 : [('key1', 4), ('key3', 6), ('key2', 8)] The original list 2 : [('key2', 1), ('key1', 4), ('key3', 2)] The grouped summation tuple list is : [('key2', 9), ('key1', 8), ('key3', 8)]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course