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

Counting the number of list items in a dictionary's values

Can someone please explain why this code is not giving the right answer. The challenge is to count the number of courses among the values of a dictionary of teachers and their courses. I am adding the values which should give an itemized list, from which I can get a count of the individual items with the len() function?

I don't have a good grasp of using the += method.

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):
    list_of_teachers = []
    for key in dictionary.keys():
        list_of_teachers.append(key)
    return len(list_of_teachers)

def num_courses(dictionary):
    list_of_values = []
    for value in dictionary.values():
        proper_list= list_of_values + value
    return len(proper_list)

2 Answers

It’s kinda like the first one, except you do for value in values.values() For something in value Like you have to dive deeper in the dictionary..

Jeffrey James
Jeffrey James
2,636 Points

You can create a new dictionary, using a dict comprehension, so for instance, if your current dict is in the form of:

d = {key: [list, of, values], ...}

count_dict = {k: len(v) for k,v in d.items() }

you can also express logic in a dict comprehension, just like a list comprehension, eg:

count_dict = {k: len(v) for k,v in d.items() if len(v) > 3 } The above would filter the return dict to keys whose list length is greater than 3, etc...