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

this is how i completed the last challenge of dictionaries in the python collections. How would you guys have done it ?

teachers = {
    'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],
  'Kenneth Love': ['Python Basics', 'Python Collections']
}

def num_teachers(teachers):
    return len(teachers)

def num_courses(teachers):
    sum_of_courses = 0
    for courses in teachers.values():
        sum_of_courses += len(courses)
    return sum_of_courses

def courses(teachers):
    courses = []
    for key in teachers.values():
        for item in key:
            courses.append(item)
    return courses

def most_courses(teachers):
    max_courses = 0
    for key in teachers:
        if len(teachers[key]) > max_courses:
            max_courses = len(teachers[key])
            teacher_name = key
    return teacher_name

def stats(teachers):
    teacher_stats = []
    for key in teachers:
        teacher_stats.append([key,len(teachers[key])])
    return teacher_stats

Here is how i completed the challenge but what i am looking to improve is to make a more and compact smart coding, learn how to code efficiently, how would you guys improve the code, what would you guys have done differently?

1 Answer

I did it this way,but I'm getting error as 'Didn't get the right teacher name!' can you help me out in where I did wrong in the code please...

teachers={'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics','Big Data'],'Kenneth Love': ['Python Basics', 'Python Collections']}

def num_teachers(x): return len(x) def num_courses(x): count=0 for i in x.values(): #print(i) count+=len(i) return count def courses(x): courses=[] for i in x.values(): for j in i: #print(j) courses.append(j) return courses def most_courses(x): most_dict={} for i,j in x.items(): for k in x.values(): if len(j)>len(k): most_dict[i]=j print(most_dict.keys()) return most_dict.keys()

most_courses(teachers)
num_teachers(teachers) num_courses(teachers) courses(teachers)

you're trying to return a dictionary, they only want one string name of the teacher with the most courses,

Look at how i did it in the function

def most_courses(teachers):
    max_courses = 0
    for key in teachers:
        if len(teachers[key]) > max_courses:
            max_courses = len(teachers[key])
            teacher_name = key
    return teacher_name