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

Bob Fitzgerald
Bob Fitzgerald
87 Points

why isn't d.items() working with this challenge?

i tried it first with d.itervalues() but then found that itervalues doens't work with p3, so I tried d.items() in the workspace, it gave me the right answer, but the challenge isn't accepting it...

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

def num_courses(d):
     print(sum(len(v) for v in d.items()))

1 Answer

andren
andren
28,558 Points

There are two issues:

  1. You are printing the result rather than returning it

  2. The items method returns both the key and value of each dictionary entry, it does not return just the values like your code seems to assume. The fact that it returns the right output when you pass in the example dictionary is basically just a lucky coincidence, since it's actually counting the wrong thing.

If you use the values method which does return the values of the dictionary like this:

def num_teachers(d):
    return len(d)

def num_courses(d):
     return sum(len(v) for v in d.values())

Then your code will work.