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

teachers.py task 2

ive tried this question but my return counts the number of lists in a list. Can anyone help me?

question: That one wasn't too bad, right? Let's try something a bit more challenging. Create a new function named num_courses that will receive the same dictionary as its only argument. The function should return the total number of courses for all of the teachers.

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 (dictofteachers):
    return len(dictofteachers)

def num_courses(dictofteachers):
    listofvalues = dictofteachers.value()
    return len(listofvalues) 

3 Answers

Opanin Akuffo
Opanin Akuffo
4,713 Points

Try this

def num_courses(dic):
    number = []
    for v in dic.values():
        number += v
    return len(number)
james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

one way is to use the dict.items() method, which allows you to loop through the keys and values of a dict, like for k,v in myDict.items(): you can then access properties of the keys and values and do what you need to do.

def num_courses(teachesr): courses = [] for course in teachesr.values(): courses += course return len(courses)

Nicely done mate. The simplest solution I came across. I was overthinking.