Python | Aggregate values ​​across tuple keys



Method # 1: Using Counter () + Expression Generator
A combination of the above functions can be used to accomplish this specific task. In this we need to first combine the same key elements and the aggregation task is performed by Counter () .

# Python3 code to demonstrate how it works
# Aggregate values ​​by tuple keys
# using Counter () + generator expression

from collections import Counter

  
# initialize the list

test_list = [( `gfg` , 50 ), ( `is` , 30 ), ( `best` , 100 ), 

  ( `gfg` , 20 ), ( `best` , 50 )]

 
# printing the original list

print ( "The original list is:" + str (test_list))

 
# Aggregate values ​​by keys tuple
# using Counter () + generator expression

res = list (Counter (key for key, num in test_list 

for idx in range (num)). items ())

 
# print result

print ( " List after grouping: " + str (res) )

Output:

 The original list is: [(`gfg`, 50), (` is`, 30), (`best `, 100), (` gfg`, 20), (`best`, 50)] List after grouping: [(` best`, 150), (`gfg`, 70), (` is`, 30)] 

Method # 2: Using groupby () + map () + itemgetter () + sum ()
Combination the above functions can also be used to accomplish this specific task. In doing so, we group the items using groupby (), the key index solution is given by itemgetter. The task of addition (aggregation) is performed by the sum () function, and the expansion of the logic for all tuples — map ().

# Python3 code to demonstrate how it works
# Aggregate values ​​by tuple keys
# using groupby () + map () + itemgetter () + sum ()

from itertools import groupby

from operator import itemgetter

 
# initialize the list

test_list = [( ` gfg` , 50 ), ( `is` , 30 ), ( `best` , 100 ),

  ( ` gfg` , 20 ), ( `best` , 50 )]

 
# print original list

print ( "The original list is:" + str (test_list))

  
# Aggregate values ​​by key am tuple
# using groupby () + map () + itemgetter () + sum ()

res = [(key, sum ( map (itemgetter ( 1 ), ele)))

for key, ele in groupby ( sorted (test_list, key = itemgetter ( 0 )), 

key = itemgetter ( 0 ))] 

 
# print result

print ( "List after grouping:" + str (res))

Output:

 The original list is: [(`gfg`, 50), (` is`, 30) , (`best`, 100), (` gfg`, 20), (`best`, 50)] List after grouping: [(` best`, 150), (`gfg`, 70), (` is` , 30)]