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

teacher stats challenge task 5

Hey, I am very new and I am having trouble understanding exactly what is going on with this solution to the stats challenge task 5.

def stats(dict):
    inner_list = []
    list_of_lists = []
    for key in dict:
        inner_list.append(key)
        inner_list.append(len(dict[key]))
        list_of_lists.append(inner_list)
        inner_list = []
    return list_of_lists  

Specifically I am not understanding exactly what is going on with inner_list.append(len(dict[key])) How does this gather the total courses? It doesn't seem to address the values in the dict at all. What am I missing here?

I saw another example of a solution that makes more sense to me:

def stats(dict):
    master_list = []
    for teacher, courses in dict.items():
        inside_list = [teacher, len(courses)]
        master_list.append(inside_list)
    return master_list

I'd really appreciate some help in understanding this better. Thanks!

1 Answer

Make no mistake, the later answer is the better one, it's shorter and more readable, so if you understand that, you're doing great. The upper answer does the same thing, and I'll try to explain why using some code:

my_dict = {'entry1': ['a', 'b', 'c'], 'entry2': [1, 2, 3]}

#using keys only
for key in my_dict:
    print (my_dict[key]) #access the values via the key

#returns 
#[1, 2, 3]
#['a', 'b', 'c']

#using keys and values
for keys, values in my_dict.items():
    print(values) #access directly with value

#returns 
#[1, 2, 3]
#['a', 'b', 'c']

#my_dict[key] in example one refers to the same value as values does in example2

for keys, values in my_dict.items():
    print(len(values))

#3
#3

for key in my_dict:
    print (len(my_dict[key])) 

#3
#3

Using the "key, values in dict.items()", the values variable is basically equal to dict[key].

Hopefully that made some sense, let me know if I can further clarify anything!

Thanks Cooper, that is helpful.

Thank you for this explanation it really helped me solve the challenge.