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

Jesse Heikkinen
Jesse Heikkinen
3,474 Points

Task 4 problem (most_courses)

So just out of curiosity, what is wrong with my code? most_courses function.

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(dict):
    return len(dict)

def num_courses(dict):
    courses = 0
    for value in dict.values():
        for val in value:
            courses += 1
    return courses

def courses(dict):
    list_courses = []
    for value in dict.values():
        for val in value:
            list_courses.append(val)
    return list_courses

def most_courses(dict):
    most_classes = 0
    class_count = 0
    name = ""
    for teacher in dict.keys():
        for classes in teacher:
            class_count += 1
        if class_count > most_classes:
            most_classes = class_count
            teacher = key
        class_count = 0
    return teacher

1 Answer

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

dict.keys is putting the string value of the teachers' names in the loop variable teacher, so when you loop through teacher in the nested for loop, you are actually looping through the letters in the teachers' names, so your count is counting letters not classes. an alternate method would be the dict.items method, which you can use like for k,v in dict.items(), and you can look at the length of v and compare to your most variable, and update the most variable and k as the teacher with the most classes if necessary.

Jesse Heikkinen
Jesse Heikkinen
3,474 Points

Ok, thanks for putting my mind to rest. I tried figuring it out myself for almost an hour and just couldn't figure out what was wrong with my function... As you may have guessed im fairly new to programming :D