w3resource

Python: Calculate the maximum aggregate from the list of tuples (pairs)


24. Calculate the Maximum Aggregate from a List of Tuple Pairs

Write a Python program to calculate the maximum aggregate from the list of tuples (pairs).

Sample Solution:

Python Code:

# Import the defaultdict class from the collections module
from collections import defaultdict

# Define a function 'max_aggregate' that finds the maximum aggregate value in a list of tuple pairs
def max_aggregate(st_data):
    # Create a defaultdict 'temp' to store and aggregate marks for each student
    temp = defaultdict(int)
    
    # Loop through the list of tuples 'st_data' containing student names and marks
    for name, marks in st_data:
        # Update the 'temp' dictionary to aggregate the marks for each student
        temp[name] += marks
    
    # Find the student with the maximum aggregate using 'max' and a key function
    return max(temp.items(), key=lambda x: x[1])

# Create a list of tuple pairs 'students' with student names and marks
students = [('Juan Whelan', 90), ('Sabah Colley', 88), ('Peter Nichols', 7), ('Juan Whelan', 122), ('Sabah Colley', 84)]

# Print a message to indicate the display of the original list
print("Original list:")

# Print the content of 'students'
print(students)

# Print a message to indicate the display of the maximum aggregate value
print("\nMaximum aggregate value of the said list of tuple pair:")

# Call the 'max_aggregate' function with 'students' and print the result
print(max_aggregate(students)) 

Sample Output:

Original list:
[('Juan Whelan', 90), ('Sabah Colley', 88), ('Peter Nichols', 7), ('Juan Whelan', 122), ('Sabah Colley', 84)]

Maximum aggregate value of the said list of tuple pair:
('Juan Whelan', 212)

Flowchart:

Flowchart - Python Collections: Calculate the maximum aggregate from the list of tuples (pairs).

For more Practice: Solve these Related Problems:

  • Write a Python program to group tuples by the first element and then calculate the total sum of the second elements for each group.
  • Write a Python program to use dictionary aggregation to sum values for duplicate keys in a list of tuple pairs.
  • Write a Python program to implement a function that returns the key with the maximum aggregated sum from a list of tuples.
  • Write a Python program to use collections.defaultdict to accumulate values from a list of tuples and then identify the key with the highest total.

Python Code Editor:

Previous: Write a Python program to get the frequency of the tuples in a given list.
Next: Write a Python program to find the characters in a list of strings which occur more than and less than a given number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.