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

Daniel Bourke
Daniel Bourke
3,870 Points

Unable to correctly count number of values in a dictionary

For the most_courses function. I'm trying to return the key (teachers name) with the most number of values. I've been stuck on this problem for a while but can't seem to figure it out.

My logic is:

  • Loop through the dictionary
  • Create a variable (maxcount) that keeps track of the key with the highest number of values
  • Loop through the dictionary again
  • Compare maxcount to the values in the dictionary a second time
  • If there's a match, return the key

Any help would be greatly appreciated!

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_users):
    return len(dict_users.keys())

def num_courses(dict_users):
    course_count = []
    for item in dict_users.values():
        course_count += item
    return len(course_count)

def courses(dict_users):
    all_courses = []
    for x in dict_users.values():
        all_courses.extend(x)
    return all_courses

def most_courses(dict_users):
    maxcount = max(len(v) for v in dict_users.values())
    for k, v in dict_users.items():
        if len(v) == maxcount:
        return k
Daniel Bourke
Daniel Bourke
3,870 Points

I think I found the answer! My return k (in most_courses) wasn't indented correctly.

If anyone has any different ways of solving this, I'd still love to see them, please.

Kurt L
Kurt L
22,856 Points

I think you just need to indent the "return k" line once more.