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

Jim Heckler
Jim Heckler
1,349 Points

Function seems to work in workspace but fails in exercise

The exercise asks to create a function called courses() that returns all courses from a dictionary. I used the dictionary as provided in the example

d = {'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],'Kenneth Love': ['Python Basics', 'Python Collections']}

When I run courses(d) in the workspace, I get this output:

['jQuery Basics', 'Node.js Basics', 'Python Basics', 'Python Collections']

Why does this not pass in the exercise?

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

def num_courses(dic):
    y = 0
    for x in dic.values():
        y += len(x)
    return y

def courses(dic):
    m = []
    for x in dic.values():
        m.append(x)
    n = []
    for i in range(0,len(m)):
        for j in range(0,len(m)):
            n.append(m[i][j])
    return n

1 Answer

Hi there!

I suspect the problem is that your example only works if the number of items in each key's value is the same as the number of items in the dictionary. The list stored in m by the example dictionary is two nested lists each with 2 items in it. If you add one course to one of the teachers in the dictionary, it will get missed and if you add a teacher, so there's three teachers and two courses per teacher you'll get an IndexError.

Just a reminder that we can loop through a dictionary like this:

for key in dic:
    for item in dic[key]

Hope it helps!

PS, try to avoid getting in the habit of using single character variable names - they're a nightmare to come back to or for others to read :)

Jim Heckler
Jim Heckler
1,349 Points

Hi Jon,

Thanks for your help! I'm still getting used to dictionaries so I forgot that they could be looped through in that manner. As for the suggestion about single character names, I had a dirty feeling while doing it but I just wanted to get through the exercise. I will not make it a habit!