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

Alex Diaz
Alex Diaz
4,930 Points

Not getting the right number returned!

Could anyone possibly help me with this code challenge, i'm having a difficult time getting the right number outputted, thanks!

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

def num_courses(arg):
    for value in arg.values():
        print(value)

1 Answer

Umesh Ravji
Umesh Ravji
42,386 Points

Hi Alex, the question is asking you for the total number of courses that there are, so you need to determine how many courses each teacher has, and then total them up.

def num_courses(arg):
    total = 0
    for value in arg.values():
        # add number of courses for each teacher to the total
    return total
Alex Diaz
Alex Diaz
4,930 Points

I put "total += 1" under the for loop, getting the wrong number of courses again.

Umesh Ravji
Umesh Ravji
42,386 Points

Why would you be doing "total += 1"? That would give you the wrong number.

Each iteration, value will be a list of courses that each teacher has. So you can get the number of courses using the len function. Then you can add that value to the total.

Alex Diaz
Alex Diaz
4,930 Points

I'm honestly sorry for not understanding this but now i put "total += len(arg.values())" and it's still wrong

Umesh Ravji
Umesh Ravji
42,386 Points

Don't be sorry, unless your willing to make mistakes, you won't learn :)

def num_courses(teachers_dict):
    total = 0
    for courses_list in teachers_dict.values():
        courses_for_teacher = len(courses_list)  # obtain number of courses for teacher
        total += courses_for_teacher  # add to total
    return total

I've renamed some variables to make it easier to understand, and added comments. The values method on a dictionary returns a list of all the values, which in this case is a list containing lists, where each list contains the courses that the teacher takes.

If you would like something explained, feel free to leave a comment.

Alex Diaz
Alex Diaz
4,930 Points

Thank you so much! I really appreciate it