w3resource

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

Python Collections: Exercise-24 with Solution

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

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/collections/python-collections-exercise-24.php