Grouped summation of tuple list in Python

PythonServer Side ProgrammingProgramming

When it is required to find the grouped summation of a list of tuple, the 'Counter' method and the '+' operator need to be used.

The 'Counter' is a sub-class that helps count hashable objects, i.e it creates a hash table on its own (of an iterable- like a list, tuple, and so on) when it is invoked.

It returns an itertool for all of the elements with a non-zero value as the count.

The '+' operator can be used to add numeric values or concatenate strings.

Below is a demonstration for the same −

Example

Live Demo

from collections import Counter

my_list_1 = [('Hi', 14), ('there', 16), ('Jane', 28)]
my_list_2 = [('Jane', 12), ('Hi', 4), ('there', 21)]

print("The first list is : ")
print(my_list_1)
print("The second list is : " )
print(my_list_2)

cumulative_val_1 = Counter(dict(my_list_1))
cumulative_val_2 = Counter(dict(my_list_2))
cumulative_val_3 = cumulative_val_1 + cumulative_val_2  
my_result = list(cumulative_val_3.items())

print("The grouped summation of list of tuple is : ")
print(my_result)

Output

The first list is :
[('Hi', 14), ('there', 16), ('Jane', 28)]
The second list is :
[('Jane', 12), ('Hi', 4), ('there', 21)]
The grouped summation of list of tuple is :
[('Hi', 18), ('there', 37), ('Jane', 40)]

Explanation

  • The required packages are imported.
  • Two list of tuples are defined, and are displayed on the console.
  • Both of these list of tuples are converted to dictionaries.
  • They are added using the '+' operator.
  • This result is converted to a list, by using only the 'values' of the dictionary.
  • This operation's data is stored in a variable.
  • This variable is the output that is displayed on the console.
raja
Published on 13-Mar-2021 05:27:30
Advertisements