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 trialMit Sengupta
13,823 PointsWhat is the wrong with the 3rd challenge?
Here's my code :
def stats(dicts):
teachers = []
for teacher in dicts:
classes = teacher, len(dicts.values())
teachers.extend(classes)
return teachers
[MOD: added ```python markdown formatting and indentation -cf]
2 Answers
Valeshan Naidoo
27,008 PointsYou need to make classes a list since the teachers list is a list of lists.
Also I used append rather than extend since the lists [teacher, no. of classes] are supposed to be separate lists (e.g. teachers = [[Kenneth Love, 2], [Jason Seifer, 3]] rather than fused into one list.
def stats(dicts):
teachers = []
for teacher in dicts:
classes = [teacher, len(dicts[teacher])]
teachers.append(classes)
return teachers
Chris Freeman
Treehouse Moderator 68,441 PointsYou wish to find the length of the teacher
value in dict
, not the length of all values
in the whole dicts
. dicts.values()
returns an interable of all the values in the whole dictionary,
def stats(dicts):
teachers = []
for teacher in dicts:
classes = [teacher, len(dicts[teacher])] # <-- changed from len(dicts.values())
teachers.append(classes) # <-- changed to append
return teachers
EDIT: fixed classes
to be a list instead of a tuple
EDIT2: typo: extend
should have been append
. code above updated.
John Judge
3,527 PointsJohn Judge
3,527 PointsVALESHAN NAIDOO Could you explain line 4, please?
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsHi John, Thanks for your comment. In reviewing my code, there was a typo/error, in that, I had
extend
instead ofappend
. Valeshan's code is correct.extend
will take all off the items within an iterable, such as a list or a string, and individual append them to a list.append
takes a single argument which will be appended to a list as a single object. By usingappend
, the list created and assigned toclasses
will be appended as a single object to theteachers
list, this preserving the "list of lists" structure.Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsValeshan, I'm changing your as to be Best Answer!