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 trialJay Reyes
Python Web Development Techdegree Student 15,937 PointsChallenge 5 of Stats. This is working on my sandbox...
def stats(dic):
list_of_teachers = []
num_courses = 0
for each in dic:
iter_list = []
iter_list.append(each)
for course in dic.values():
num_courses += len(course)
iter_list.append(num_courses)
list_of_teachers.append(iter_list)
return list_of_teachers
2 Answers
Jeff Muday
Treehouse Moderator 28,720 PointsYour approach is pretty good, but has problems with how it counts courses for each teacher. The inner loop is basically counting all the courses and then accumulating this in num_courses.
You can fix it like this:
def stats(dic):
list_of_teachers = []
num_courses = 0
for each in dic:
iter_list = []
iter_list.append(each)
courses = dic[each] # get rid of the loop, get the courses based on each (teacher name)
num_courses = len(courses) # get the length
iter_list.append(num_courses)
list_of_teachers.append(iter_list)
return list_of_teachers
We can simplify it a little using the dic.items() which returns key/value pairs of the name and the courses. Then, it is super easy to append to your list of teachers/courses.
def stats(dic):
list_of_teachers = []
for name, courses in dic.items():
num_courses = len(courses) # number of courses is simply calculated with len
list_of_teachers.append([name, num_courses])
return list_of_teachers
Jeff Muday
Treehouse Moderator 28,720 PointsPython is a fun language, there is so much you can do with it!
Jay Reyes
Python Web Development Techdegree Student 15,937 PointsJay Reyes
Python Web Development Techdegree Student 15,937 PointsThanks! I really took the long way with my initial approach.