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

Hai Phan
Hai Phan
2,442 Points

How to sort a list of tuple by the length of second element?

This is for challenge 4 in Dictionary course. First, I have a dictionary like this

{'teacher1': [course1, course2], 'teacher2': [course3, course4, course5]}

then I use .items() method to create a list of tuple with teacher/course pair values. Now I want to sort them to find the teacher with most courses. But got bummer every time! I think have problem understanding how to use the .sorted() method. Can someone help me please?

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 (TH_teacher):
    return len(TH_teacher)
def num_courses (TH_courses):
    course_list = []
    for course in TH_courses.values():
        course_list += course
    return len(course_list)
def courses (TH_courses):
    course_list = []
    for course in TH_courses.values():
        course_list.extend(course)
    return course_list
def most_courses (TH_courses):
    courses_list = TH_courses.items()
    new_list = sorted(courses_list, key=lambda x: x[1], reverse=True)
    return new_list[0]

1 Answer

Ernestas Petruoka
Ernestas Petruoka
1,856 Points

Well I am student so I could be wrong, but I do not see why do you need use sorted() method in this challange. You simply need compare teachers and find which one have more courses. I passed this challange simply looping in teachers and finding biggest lenght dictionare (d variable) and then teacher who have biggest lenght dictionare have most courses.

My code looks like this:

def most_courses(dict):
    d = 0
    n = ()
    for value1 in dict.copy():
        if len(dict[value1])> d:
            d = len(dict[value1] )
            n = value1
    return n

Hope this would help :)

Hai Phan
Hai Phan
2,442 Points

Thank you for the answer! Maybe I make thing way too complicated :)