Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (Retired) Dictionaries Teacher Stats

Małgorzata Staniszewska
Małgorzata Staniszewska
2,431 Points

Problem with Python

I have received feedback:"Well done" after the first part of the task and now it doesn't work. Why?

teachers.py
# The dictionary will be something like:
# {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],
#  'Kenneth Love': ['Python Basics', 'Python Collections']}
#
# Often, it's a good idea to hold onto a max_count variable.
# Update it when you find a teacher with more classes than
# the current count. Better hold onto the teacher name somewhere
# too!
#
# Your code goes below here.

def most_classes(dictionary):
    max_count = 1
    for name in dictionary:
        count = len(dictionary[name])
        if count > max_count:
            max_count = count
        if len(dictionary[name]) == max_count:
            return(name)
def num_teachers(dictionary):
    list_t = []
    for name in dictionary:
        list_t.append(name)
        return(len(list_t))

1 Answer

As your function is written it will return the first teacher that it gets. If it got the correct answer the first time, it would pass, but any other time it won't. Your function is checking on the same for loop. You should have it going over the dictionary with a second for loop or store the teacher's name.

This function will pass every time. It stores the teacher and doesn't have to go over the dictionary again to find the teacher.

def most_classes(dictionary):
    most_classes_count = 0
    most_classes_teacher = None
    for teacher in dictionary:
        if len(dictionary[teacher]) > most_classes_count:
            most_classes_count = len(dictionary[teacher])
            most_classes_teacher = teacher
    return most_classes_teacher