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

Create a function, most_courses that takes a teacher dictionary. return the teacher with the most courses

I got this code from stackoverflow. It works local but won't pass the challenge. Any glaring errors?

def most_courses(dct):
    teacher = max(dct.keys(), key=(lambda k: dct[k]))
    return teacher

Tagging Chris Freeman for his amazing answers :smile:

Also tagging Kenneth Love in case there's a glitch in the code challenge. (Your program seems to work on my machine, too.)

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,987 Points

The SO snippet has an error and does not produce the correct results. Once corrected, it passes Task 4 of the challenge so the validator seems to be working fine. The error is the lambda function.

The max function iterates over each element in the first parameter: the keys of the dict – the teacher names. If a key argument is present, the max function will use this argument (the lambda function) to evaluate each of these teacher names. In this code, each teacher name is passed to the lambda function as the argument k. The results of the lambda function is used as the basis for determining the maximum value.

So what does the existing lambda function do? It returns the value of the dictionary lookup using the teacher name. The result is the actual full list of each teacher's courses. Comparing in this way, the "max" is based on the alphabetical ordering of the first element in each list. That is, the starting character of the first course. Clearly not what you're looking for.

How can you change the lambda function to return the length of each list instead of returning the full list? Hint: I was able to add 5 characters to the lambda function to pass the task.

Post back if you're stuck.

If you have not covered lambda functions yet in your studies, I suggest trying to solve the most_courses task using a different technique. Good luck!!

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

On my phone so I can't check the validator but...Do you understand what's going on in this? I'm not a fan of answers copied and pasted from SO, as I'm sure you can understand.