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

bowei zhou
bowei zhou
1,762 Points

python not working or pass the test

That one wasn't too bad, right? Let's try something a bit more challenging. Create a new function named num_courses that will receive the same dictionary as its only argument. The function should return the total number of courses for all of the teachers.

def num_teacher(course): return len(course)

num_teacher(course)

total_num = [] def num_courses(course): for teacher in course: num_course = len(course[teacher]) total_num.append(num_course) total_num_course = sum(total_num) return total_num_course

num_courses(course)

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_teacher(course):
    return len(course)


total_num = []
def num_courses(course):
    for teacher in course:
        num_course = len(course[teacher])
        total_num.append(num_course)
    total_num_course = sum(total_num)
    return total_num_course   

1 Answer

The solution is as follow:

  1. Take the dictionary in the function
  2. loop over each teacher
  3. Do a lookup in the dictionary with the teacher's name
  4. Get the length of the lookup(courses array) as it denotes the number of courses
  5. Accumulate the number of courses in the count variable to add all of the courses
  6. Return the count
def num_courses(teachers_dict):
    count = 0
    for teacher in teachers_dict:
        count = count + len(teachers_dict[teacher])

    return count