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 trialDezhi Zhu
2,662 PointsI need help please
Create a new function named num_courses that will receive the same dictionary as its only argument. The function should return the total number of courses for all of the teachers.
What's wrong with my code? It works perfectly fine
# 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):
num = len(arg.keys())
return(num)
def num_courses(arg):
leng = 0
for lista in arg.values():
leng = leng + len(arg)
return(leng)
1 Answer
Rich Zimmerman
24,063 PointsYou're adding the length of the actual dict - so the number of keys, not the number of values.
The other issue is you're adding the number of values, which for each key is only 1 - but the challenges wants the total number of courses.
# {'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],
# 'Kenneth Love': ['Python Basics', 'Python Collections']}
so the keys are "Andrew Chalkley" and "Kenneth Love", and they each have one value, which is a list. You want to know the length of the list, not the length of arg.values() (which is just a 2 dimensional list)
You can do something like this, which unpacks the key and value for each Key : Value pair in the dict.
def num_courses(arg):
answer = 0
for key, value in arg.items():
# key = the teacher's names
# value = the list of courses
answer += len(value)
return answer