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 (Retired) Dictionaries Dictionary Iteration

Mit Sengupta
Mit Sengupta
13,823 Points

What 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
Valeshan Naidoo
27,008 Points

You 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
John Judge
John Judge
3,527 Points

VALESHAN NAIDOO Could you explain line 4, please?

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Hi John, Thanks for your comment. In reviewing my code, there was a typo/error, in that, I had extend instead of append. 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 using append, the list created and assigned to classes will be appended as a single object to the teachers list, this preserving the "list of lists" structure.

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

You 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.