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

Dictionary Iteration Challenge 2 of 5

I can't figure out what's wrong with this code. It keeps bringing up a "TypeError". Thanks!

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(dictionary):
    number_of_teachers = len(dictionary)
    return number_of_teachers

def num_courses(dictionary):
    for value in dictionary.values():
        return sum(len(value))

1 Answer

When I copy and paste your code, I get this error:

Traceback (most recent call last):                                                               
  File "teachers.py", line 46, in <module>                                                        
    num_courses(dictionary)                                                                      
  File "teachers.py", line 41, in num_courses                                                     
    return sum(len(value))                                                                       
TypeError: 'int' object is not iterable  

It's referring to this in your code:

return sum(len(value))

The error can be resolved by removing "sum." However, there is still the issue of your code is only returning the length of a single pass through the teachers (ie. just Andrew's courses). I think you were trying to solve this with sum, but sum does not retain the total with each time through the loop.

I found this challenge easier by keeping count with an int variable and adding the len to the variable each time through the for loop. It might look something like this:

course_count = 0
for value in dictionary:
    course_count += len(dictionary[value])

Keep in mind, the courses are a list inside a dictionary, that's why you want dictionary[value].