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 trialShahid Mohamed Islam
4,371 PointsIs there a better way? - Python
My code passes but just want to know if there's a better way of doing the task below. My code seems convoluted and doesn't consider several 'teachers' doing the same number of 'courses'.
Task: Create a function named most_courses that takes our dictionary. It should return the name of the teacher with the most courses. You might need to hold onto some sort of max count variable.
# The dictionary will look something like:
# {'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],
# 'Kenneth Love': ['Python Basics', 'Python Collections']}
def most_courses(some_dict):
new_dictionary = {}
for key in some_dict.keys(): #Iterating through each teacher in dictionary
number_of_courses = len(some_dict[key]) #Number of courses of teacher
new_dictionary.update({number_of_courses:key}) #Creating a new dictionary with number_of_courses as key and teacher as value.
#...I do this so I can search for the max length and find the associated teacher name
most_course_amount = max(new_dictionary.keys()) #most_course_amount = maximum number of courses.
busiest_teacher = new_dictionary[most_course_amount]#busiest_teacher = the teachers name associated with
# ...most_course_amount
return busiest_teacher
1 Answer
Steven Parker
231,269 PointsThis is about the most efficient (or at least most concise) solution I've seen:
def most_courses(dict):
return max(dict, key=lambda k: len(dict[k]))
In the case of a "tie", it would simply return the first one just like your version does. Given the instructions, I'm not sure you could do anything else in that situation.