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 (2016, retired 2019) Dictionaries Teacher Stats

Thomas McDonnell
Thomas McDonnell
8,212 Points

Why 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

teachers.py
# 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
Steven Parker
231,248 Points

Well, 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
Thomas McDonnell
8,212 Points

Thanks Steven, you have no idea how long I spent thinking on that :)

Steven Parker
Steven Parker
231,248 Points

Happy to help. Did you finally arrive at the one-liner using the comprehension?

Thomas McDonnell
Thomas McDonnell
8,212 Points

Nope 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
Steven Parker
231,248 Points

You 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
Thomas McDonnell
8,212 Points

Now that looks pythonic :):) and makes sense