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

Emil Hejlesen
Emil Hejlesen
3,014 Points

How do you do this?

please help

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.

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

def num_teachers(dict):
    num_teachers = 0
    for x in dict.keys():
        num_teachers += 1
    return num_teachers

def num_courses(dict):
    courses = 0
    for x in dict.values():
        for y in x:
            courses += 1
    return courses

def courses(dict):
    list = []
    for x in dict.values():
        for y in x:
            list.append(y)
    return list

def most_courses(dict):
    high = 0
    for teacher in dict:
        if len(dict[teacher]) > high:
            boss = []
            boss.append(teacher)
    return "".join(boss)


def stats(dict)
    total = []
    for x in dict:
        total.append([x])

1 Answer

Sumit Chawla
Sumit Chawla
20,050 Points

I would do it as follows. Not clear what you wish to do for the stats part, but I'm assuming you can build that easily with the rest of the functions. Also: dict is a reserved word so don't use that as a variable name.

def num_teachers(d):
    return len(d)

def num_courses(d):
    return len(courses(d))

def courses(d):
    return [i for _, item in d.items() for i in item]

def most_courses(d):
    highest = max(len(d[x]) for x in d.keys())
    boss = [k for k,v in d.items() if len(v) == highest]
    return ",".join(boss)

Here's the output for your example:

>>> dictionary
{'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'], 'Kenneth Love': ['Python Basics', 'Python Collections']}
>>> num_teachers(dictionary)
2
>>> num_courses(dictionary)
4
>>> courses(dictionary)
['jQuery Basics', 'Node.js Basics', 'Python Basics', 'Python Collections']
>>> most_courses(dictionary)
'Andrew Chalkley,Kenneth Love'
>>> dictionary['Kenneth Love'].append('Django Fantastico')
>>> most_courses(dictionary)
'Kenneth Love'