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

Paulhan Carre
Paulhan Carre
1,368 Points

Teachers stats step 1

I started several attempts but I am still very noob in python, any pointers with included logic would be very helpful. Yours Truly: Pipemaster P

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.
dic = {'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],
'Kenneth Love': ['Python Basics', 'Python Collections']}
def num_teachers(dic):
    counts = []
for key in dic:
    counts.append(len(dic[key]))
    return counts

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,426 Points

You're slightly off track in solving the task: "The num_teachers function should return an integer for how many teachers are in the dict."

Let's get your code back on track. First there are some indentation issues. The for loop needs to be indented:

def num_teachers(dic):
    counts = []
    for key in dic: #for each teacher
        # append the length of the dict value 
        counts.append(len(dic[key]))
    return counts # return list of values

In the comments, you can see you are returning a list of values representing the number of courses each teach has.

Instead, you want to count the number of teachers themselves not their courses, and also want to return the sum of the values. These are corrected below:

def num_teachers(dic):
    counts = []
    for key in dic:
        counts.append(1) # add one teacher 
    return sum(counts) # return sum

This is basically just counting the number of dict keys. This can be done without a for loop.

def num_teachers(dic):
    counts = len(dic.keys())
    return counts

Since the length of a dict is the same as the number of keys this can be reduced to:

    counts = len(dic)

The most reduced option did not work for me as an answer.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,426 Points

Which solution did you try? Please post your code.