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 (Retired) Dictionaries Teacher Stats

chiu szu ting
chiu szu ting
2,318 Points

other way to write this task?

a passed this task by writing the code below,but the #instructions told me to use the max_count variable, so i think there might be another way to write the code, but i have no idea, someone help me about these?

teachers.py
# The dictionary will be something like:
# {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],
#  'Kenneth Love': ['Python Basics', 'Python Collections']}
#
# Often, it's a good idea to hold onto a max_count variable.
# Update it when you find a teacher with more classes than
# the current count. Better hold onto the teacher name somewhere
# too!
#
# Your code goes below here.
def most_classes(dicts):
    dicts={'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],
         'Kenneth Love': ['Python Basics', 'Python Collections']}
    lists={}
    for key in dicts:
        lists.update({key:len(dicts[key])})
    for teacher in lists:
        if lists[teacher] == (max(lists.values())):
            return(teacher)

1 Answer

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

Hi there.

Here the alternative solution, using only 1 for loop, the code is pretty easy to read, I think you should have no problem understanding it.

def most_classes(dic):
    teacher = ""                        # name of the teacher w/ most classes
    most_class = 0                      # numbers of the most classes
    for key in dic:
        if len(dic[key]) > most_class:  # if this teacher has more classes
            most_class = len(dic[key])  # re-assign most_class variable
            teacher = key               # re-assign teacher's name
    return teacher

Later when you finish the Python functional programming course, it'll be possible to have a simpler and more effecient solution by using the lambda expression like this.

def most_classes(dic):
    return max(dic, key=lambda i: len(dic[i]))

Hope it helps

chiu szu ting
chiu szu ting
2,318 Points

the lambda expression was so neat and nice!!! hope i can get how it works in the later course~