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 (2016, retired 2019) Dictionaries Teacher Stats

most_courses returns wrong value

Tested this code in Workspaces with a sample dictionary and it seems to work, but I'm getting a "Didn't get the right teacher name" error no matter what I try. What am I missing?

teachers.py
# The dictionary will look something like:
# {'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],
#  'Kenneth Love': ['Python Basics', 'Python Collections']}
#
# Each key will be a Teacher and the value will be a list of courses.
#
# Your code goes below here.

def num_teachers(teachers):
    return int(len(teachers))

def num_courses(teachers):
    course_total = 0
    for teacher in teachers:
        course_total += int(len(teachers[teacher]))
    return course_total

def courses(teachers):
    course_list = []
    for teacher in teachers:
        course_list.extend(teachers[teacher])
    return course_list

def most_courses(teachers):
    max_count = 0
    max_teacher = None
    for teacher in teachers:
        if len(teacher) > max_count:
            max_teacher = teacher
            max_count = len(teacher)
    return max_teacher

2 Answers

Stuart Wright
Stuart Wright
41,120 Points

When you loop over a dictionary as you have:

for teacher in teachers:

You are looping over the keys, not the values. So when you check for the length of teacher in your next line, you are checking the length of the key, not the values. To loop over keys and values, you can use:

for teacher, courses in teachers.items():

Now the teacher variable is the current key in the loop, and courses is the current value.

You'll need to change a couple of other things inside the loop as a result, but I'll leave that for you to work out.

thanks!