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

Need help on the following question

Create a function named most_courses that takes our good ol' teacher dictionary. most_courses should return the name of the teacher with the most courses. You might need to hold onto some sort of max count variable.

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(a_dic):
    return len(a_dic.keys())

def num_courses(a_dic):
    hua=0
    for each in a_dic.values():
        hua+=len(each)
    return hua

def courses(a_dic):
    a_list=[]
    for b in a_dic.values():
        a_list.extend(b)
    return a_list

1 Answer

The challenge requires you to return the name of the teacher who teaches the most courses. In order to do this, you will need to create two variables: one to hold the number of courses and one to hold the teacher name. Then you will need to go through the dictionary to access both the key (teacher) and values (courses). You will need to determine if the number of courses for that teacher is greater than the current value stored in the variable you created to hold the number of courses. If it is greater, then you should store the name of that teacher in the variable you created to hold a teacher name. After you have looped through all of the key, value pairs you should have the name of the teacher who teaches the most courses which you can then return.

My solution looks like this...

def most_courses(dic):
    course_count = 0
    teacher_name = '' 

    for teacher, courses in dic.items():
        if len(courses) > course_count:
            teacher_name = teacher
    return teacher_name