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

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
Chris Freeman
Treehouse Moderator 68,423 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
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.