Python | Multiple Keys Grouped Summation

In this program, we have a list of tuples and indexing lists. We need to create a Python program that will perform multiple keys grouped summation using the given key lists.
Submitted by Shivang Yadav, on October 30, 2021

While coding in Python programming language, we might come across situations where we have a collection and we need to extract or perform some tasks based on given key conditions to returning the result. In this article, we will see a program in Python that will perform multiple keys grouped summation.

TupList = [(32, 'A', 'Python'), (35, 'A', 'Python'), (12, 'B', 'C')]

groupingIndex = [1, 2][Indices to group]

sumIndex = [0][Indices to sum]

[(67, 'A', 'Python'), (12, 'B', 'C')]

Before going further with the problem, let's recap some basic topics that will help in understanding the solution.

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.


tuple = ("python", "includehelp", 43, 54.23)

Performing Multiple Keys Grouped Summation

To solve the problem, we need to group the keys based on the summation for the given condition. For this, we will be using list comprehension to perform summation of keys of groups created using a loop.

from collections import defaultdict
# Creating and printing the List 
test_list = [(32, 'A', 'Python'), (35, 'A', 'Python'), (12, 'B', 'C programming language')]
print("The initial List of tuples is : " + str(test_list))

# Creating grouping and summation index lists
groupingIndex = [1, 2]
sumIndex = [0]
# Performing grouping summation
defDict = defaultdict(int)
for sub in test_list:
    defDict[(sub[groupingIndex[0]], sub[groupingIndex[1]])] += sub[sumIndex[0]]
keyGrouping = [key + (val, ) for key, val in defDict.items()]
# Printing result
print("The list after Performing multiple keys grouped summation is : " + str(keyGrouping))


The initial List of tuples is : [(32, 'A', 'Python'), (35, 'A', 'Python'), (12, 'B', 'C programming language')]
The list after Performing multiple keys grouped summation is : [('A', 'Python', 67), ('B', 'C programming language', 12)]

Python Tuple Programs »

Related Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.