'Loop to get the maximum value with key in a dictionary

I'm trying to get the person who did the most course into my summary function. I found that the way to access those elements is using for key, values in students.items(). When I used print(len(values)), I found that it printed out the amount of courses of each student did 5,0,4 but I'm having trouble only printing out the highest number of courses done and making sure the student's name is printed along with it. I tried to use max() but got int object is not subscriptable.

from operator import itemgetter

def add_student(students,name):
    students[name] = set()

def print_student(students, name):
    
    if name not in students:
        print(f"{name} does not exist in the database")
    else:
        print(f"{name}:")
        print(f"Number of completed courses: {len(students[name])}")
        for course in students[name]: #printing out the contents of the tuple
          print(f"{course[0]} ({course[1]})")
        total_score = 0
        for course in students[name]:   
            total_score += course[1]
            
        try:
            print(f"average grade : {total_score/len(students[name])}")
        except ZeroDivisionError:
            print("no completed courses")
                 
    
def add_course(students,name, course:tuple):
    if course[1] == 0:
        return 0
    students[name].add(course)
    
def summary(students):
    new_set = ()
    print(f"students {len(students)}")
    for key, values in students.items():
        print(len(values))
    
        
    
        

 
   
students = {}
add_student(students, "Peter")
add_student(students,"Kristina")
add_student(students, "Eliza")
add_course(students, "Peter", ("EECS 2011", 70))
add_course(students, "Peter", ("EECS 1015", 52))
add_course(students, "Peter", ("EECS 245", 42))
add_course(students, "Peter", ("EECS 2412", 52))
add_course(students, "Peter", ("EECS 2030", 53))
add_course(students, "Eliza", ("EECS 43", 3))
add_course(students, "Eliza", ("EECS 52", 72))
add_course(students, "Eliza", ("EECS 43", 72))
add_course(students, "Eliza", ("EECS 74", 72))
print_student(students, "Peter")
print("--------------")
print_student(students,"Eliza")
print("------summary here-------")
summary(students)


Solution 1:[1]

You can take the maximum of the keys of the students dictionary, using the length of the corresponding value (i.e. number of courses) as the key to compare on:

def summary(students):
    student_with_most_courses = max(students.keys(), key=lambda x: len(students[x]))
    print(student_with_most_courses)

This outputs:

Peter

Solution 2:[2]

you can short the names on bases of the no of courses and then from there take the result.

def summary(students):
    new_set = ()
    print(f"students {len(students)}")

    result =  sorted(students.items(), key =lambda x:len(x[1]),reverse=True )
    for student_name, course in result:
        print(student_name, len(course))

output

average grade : 54.75
------summary here-------
students 3
Peter 5
Eliza 4
Kristina 0 

Solution 3:[3]

I think this question was maybe discussed beforely; How do i sort a dictionary by his value? and How to get the 3 highest value items from dictionary?.

 I provide this simple code to print out each student and the number of completed courses:

def summary(students):
    [print(students.get(courses), courses) for n_courses in sorted({name:len(students[name]) for name in students}) for courses in n_courses]

Solution 4:[4]

Code of summary, almost done!

`
def summary(students):
result = [[key, len(values)] for key, values in students.items()]
result.sort(key=lambda row: row[1], reverse=True)

print(f"students: {len(students)}")

for name, number in result:
    print(name, number)
`

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BrokenBenchmark
Solution 2 sahasrara62
Solution 3
Solution 4 Mário César Fracalossi Bais