Q:

Python | Multiple Keys Grouped Summation

belongs to collection: Python Tuple Programs

0

Example:

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

Output:

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Convert List of Lists to Tuple of Tuples... >>
<< Python | Adjacent Coordinates in N dimension...