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 trialThomas McDonnell
8,212 PointsWhy am I only getting one of my list values here? If any one can help I would really appreciate it.
def courses(d): list_of_lists = [] for l in d.values(): list_of_lists.append(l) flattened = [val for sublist in list_of_lists for val in sublist] return flattened
# The dictionary will look something like:
# {'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],
# 'Kenneth Love': ['Python Basics', 'Python Collections']}
#
# Each key will be a Teacher and the value will be a list of courses.
#
# Your code goes below here.
def num_teachers(d):
return(len(d))
def num_courses(d):
count = sum(len(v) for v in d.values())
return count
def courses(d):
list_of_lists = []
for l in d.values():
list_of_lists.append(l)
flattened = [val for sublist in list_of_lists for val in sublist]
return flattened
3 Answers
Steven Parker
231,269 PointsWell, your return
statement is inside the loop, so it will return during the first pass and the loop will never finish.
But your comprehension-fu is strong! With a slight change to that comprehension, would you even need a loop?
Thomas McDonnell
8,212 PointsNope never was able to make in in the one line. I think I still have a ways to go before I can call myself PYTHONISTA!!
Steven Parker
231,269 PointsYou were so close, I was betting you would get it after that hint.
def courses(d):
return [val for sublist in d.values() for val in sublist]
Thomas McDonnell
8,212 PointsNow that looks pythonic :):) and makes sense
Thomas McDonnell
8,212 PointsThomas McDonnell
8,212 PointsThanks Steven, you have no idea how long I spent thinking on that :)
Steven Parker
231,269 PointsSteven Parker
231,269 PointsHappy to help. Did you finally arrive at the one-liner using the comprehension?