Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Dictionaries Teacher Stats

Thomas McDonnell
Thomas McDonnell
8,211 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
216,083 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,211 Points

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

Steven Parker
Steven Parker
216,083 Points

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

Thomas McDonnell
Thomas McDonnell
8,211 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
216,083 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,211 Points

Now that looks pythonic :):) and makes sense