Python Python Collections Dictionaries Teacher Stats

num_teachers challenge: why doesn't this code work?

def num_teachers(teachers_courses): teachers_courses = {} number_of_teachers = len(teachers_courses.keys()) return int(number_of_teachers)

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(teachers_courses):
    teachers_courses = {}
    number_of_teachers = len(teachers_courses.keys())
    return int(number_of_teachers)

2 Answers

Henrik Christensen
Henrik Christensen
35,673 Points

All you have to do is to return the number of teachers, and because there's only 1 teacher in each item you can do it very simple like this

def num_teachers(teachers_courses):
    return len(teachers_courses)

# this fails because
def num_teachers(teachers_courses):
    teachers_courses = {}  # here you set teachers_courses to an empty dict
    number_of_teachers = len(teachers_courses.keys())  # getting the length of the empty dict
    return int(number_of_teachers)  # returning 0 because the dict is empty
Jordan Pierre
Jordan Pierre
16,596 Points

UPDATE

I figured it out. The only problem was the code was looking for num_teachers and I had num_teacher as the name of the function.

Henrik,

I wrote my code a little differently. It worked in workspaces but not in the code challenge. I would just like to know why it's not working or if the way I wrote it is ok.

def num_teacher(teachers_list):
    teachers = len(teachers_list.keys())
    print(teachers)


num_teacher({'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],
  'Kenneth Love': ['Python Basics', 'Python Collections']})
Henrik Christensen
Henrik Christensen
35,673 Points

I'm not sure about the new code you shared, but since there is 1 teacher pr item in teachers_list you could just return len(teachers_list) like this

def num_teachers(teachers_list):
    return len(teachers_list)

Edit: The code might be failing because you print() instead of return