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

Al Craig
Al Craig
22,220 Points

def num_courses(dict_teachers): courses = set(dict_teachers.values()) return len(courses)

What am I doing wrong here? I can't get past part 2 of the dictionary question.

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

def num_courses(dict_teachers):
    courses = set(dict_teachers.values())
    return len(courses)

4 Answers

Al Craig
Al Craig
22,220 Points

It works now. I don't know if something changed behind the scenes. Thanks.

Al Craig
Al Craig
22,220 Points

Spoke to soon. It was part 1 I was passing. I get the following error:

Bummer: TypeError: unhashable type: 'list'

Ina Bankyn
Ina Bankyn
5,434 Points

Try:

sum(len(courses) for courses in dict_teachers.values())

which is the same as:

count = 0
for courses in dict_teachers.values():
    count += len(courses)

set(dict_teachers.values()) raises a TypeError: unhashable type: 'list'

Al Craig
Al Craig
22,220 Points

Thanks. I found the way through when I came back to this.

The issue was that dict_teachers.values() returns a list of lists because the dictionary values for each teacher key may contain several courses. The set() function then can't handle this list because it's looking at the groups of courses together rather than at a list of all courses. This can be overcome by concatenating the values to form a list.

This leads to the following solution...

def num_courses(dict_teachers):
    courses = []
    for course in dict_teachers.values():
        courses += course
    courses = set(courses)
    return len(courses)