Python | Group summation of a list of tuples



Method: Using + operator Counter () + + operator

This the task can be done using the Counter function as it is internally grouped, and the addition operator can be used to specify the functionality of the grouped result.

# Python3 demo code
# group summation of the list of tuples
# using Counter () + operator & quot; + & quot;

from collections import Counter

 
# initialize the list of tuples

test_list1 [( `key1` , 4 ), ( `key3` , 6 ), ( `key2` , 8 )]

test_list2 = [( `key2` , 1 ), ( `key1` , 4 ), ( ` key3` , 2 )]

 
# print original lists

print ( "The original list 1:" + str (test_list1))

print ( "The original list 2:" + str (test_list2))

 
# using Counter () + operator & quot; + & quot;
# group summation of the list of tuples

cumul_1 = Counter ( dict (test_list1))

cumul_2 = Counter ( dict (tes t_list2))

cumul_3 = cumul_1 + cumul_2 

res = list (cumul_3.items ())

 
# print result

print ( "The grouped summation tuple list is:" + str (res))

Output:

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