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 (Retired) Dictionaries Dictionary Iteration

Lance McCormick
Lance McCormick
7,553 Points

Stats Challenge (Step 3) - How can I improve my code?

This step really challenged me, but I powered through it with many tests in the python interpreter and my own code editor. My code passed the challenge but I feel like there might be an easier, more pythonic way of thinking about these things.

At first I ran into string conversion issues when trying to append stuff directly into my teachers list. But I eventually moved away from that and decided on using a sub-list and appending that to the main teachers list instead. This one really made me think hard about how I could create a list of lists.

How can I improve my code?

def stats(teacher_dict):
    teacher_list = []
    for teacher in teacher_dict:
        sub_list = ['', 0]

        name = teacher
        num_classes = len(teacher_dict[teacher])

        sub_list[0] = name
        sub_list[1] = num_classes
        teacher_list.append(sub_list)
    return teacher_list

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,082 Points

You have all the right elements. The only improvements would be to streamline the statements.

# The for loop block
        sub_list = ['', 0]

        name = teacher
        num_classes = len(teacher_dict[teacher])

        sub_list[0] = name
        sub_list[1] = num_classes
        teacher_list.append(sub_list)

# Can be replaced by
        teacher_list.append([teacher, len(teacher_dict[teacher])])

Using the dict.items() method to return both the key and the value, this can be compress further:

def stats(dct):
    result = []
    for teacher, course_list in dct.items():
        result.append([teacher, len(course_list)])
    return result
Aby Abraham
PLUS
Aby Abraham
Courses Plus Student 12,531 Points
def stats(dict):
    slist = []
    for key, value in dict.items():
        slist.append([key, len(value)])
    return slist