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
Steven Young
2,486 Pointsneed help with Python dictionary challenge 3 (create lists of lists)
If I am understanding the task correctly, it wants us to take a dictionary that contains teachers names as keys, and their classes as values. Then split each teacher/classes pair into a list, so that there is one list for every teacher, which contains two elements; the teachers name, and the number of classes he/she gives.
So here is what I have so far:
def stats(teacher_dict):
master_list = []
for teacher in teacher_dict:
child_list = []
child_list.append(teacher)
counter = 0
for values in teacher:
counter += 1
child_list.extend(str(counter))
master_list.append(child_list)
return master_list
This is working partially; it it does create a list of lists, and it gives the name of the teacher for the first element. Where it is not behaving as desired is in the second element, which is the number of classes. So how can I fix it so that it gives the number of classes for the second element of each and every list that is within the bigger list?
(now it is saying '1,2', or '1,1', or '1,4' for the second (and unwanted third) elements of the lists)
Also, if I didn't understand the task correctly, please let me know.
1 Answer
Joshua Ferdaszewski
12,716 PointsI see two potential issues in your code. The first is that your inner loop, for values in teacher: is probably not doing what you intend. The teacher variable is a string, like "Kennith". Your code is iterating over each character in the string. You probably want the list of classes that is a value in the dictionary passed in as teacher_dict. To get the value of a key in a dictionary, try this syntax, teacher_dict[teacher].
One other minor issue is that this line child_list.extend(str(counter)) is probably not what you want. extend() takes an sequence as an argument and adds that sequence to a list. Since you are changing counter from an int into a string, extend adds each character in that string as a new element in the list, probably not what you want. I would recommend keeping counter an int and using append() instead.
I hope this helps and good luck learning Python!