Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Dictionaries Teacher Stats

8,273 Points

How do I get a specific key in a dictionary?

I am trying to get the key of a dictionary if the value is equal to a maxcount variable. However, when I try to print it out, I get EVERY key instead of just the one I want. This question is specifically related to the most_courses function. Any advice on how to solve this?

# 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):

def num_courses(teachers):
    courses = []
    for value in teachers.values():

def courses(teachers):
    courses = []
    for value in teachers.values():

def most_courses(teachers):
    maxcount = max(len(value) for value in teachers.values())
    for item in teachers.items():
        if teachers.values() == maxcount:

1 Answer

Adriano Junior
Adriano Junior
5,065 Points

Hey, @drstrangequark. I feel your pain, this code challenge can be tricky.

From what I've seen in your code, you're trying to do too much just in the definition of the max_count variable. You're also looping through the wrong values. You don't want to loop through teachers.items(), but yes teachers.keys(). And also you're not returning the intended value, you're printing it. It does look like it, but they are different. Here's my suggestion for your code:

Define "teachers" if you want to test it out.

teachers = {} #This is just in case you want to test it out in workspaces first, or on your selected IDE.

def most_courses(teachers): max_count = 0 winner = "" for x in teachers.keys(): count = len(teachers[x]) if count >= max_count: max_count = count winner = x

print(winner) #This is just in case you want to test it out in workspaces first, or on your selected IDE.
return winner

most_courses(teachers) #This is just in case you want to test it out in workspaces first, or on your selected IDE.

I hope this was helpful.