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 Smith
Daniel Smith
10,172 Points

I'm not sure why my most_courses function isn't right. Its working in the external IDE i use to run practice code

If anyone can point me in the right direction I'd appreciate it

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):
    counter=0
    for keys in dict:
         if isinstance(dict[keys],list):
            counter+=len(dict[keys])
    return counter


def courses(dict):
    courses_offered=[]
    flattened=[]
    for keys in dict:
        courses_offered.append(dict[keys])
    for sublist in courses_offered:
        for val in sublist:
            flattened.append(val)
    return flattened

def most_courses(dict):
    return max(dict, key=dict.get)
Daniel Smith
Daniel Smith
10,172 Points

its supposed to return the teacher with the most courses

2 Answers

Steven Parker
Steven Parker
231,275 Points

It sounds like you may have been testing with "lucky data". Your test dictionary just happened to have the most courses in the same list with the alphabetically "higher" first title. As Daniel pointed out, the challenge is expecting the function to return the teacher with the most courses.

You solution approach is unusual and clever, but you'll need to create a companion function that will return the length of the values instead of the values themselves to use as the "key". But if you do that, it should indeed pass the challenge!

Daniel Smith
Daniel Smith
10,172 Points

def most_courses(dict): most=max(dict, key=lambda k: len(dict[k])) return most

this worked great! thanks for the direction