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

Code that appears to work doesn't

So, in task two the num_courses function seems to return 4 if i use the dict in the comment, which i assume is correct. but it doesnt pass the task.

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(arg1):
    count = 0
    for items in arg1.keys():
        count += 1
    return count

def num_courses(arg1):
    out = 0 
    for items in arg1.keys():
        for v in items:
            out += 1
    return out

1 Answer

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Rob,

The .keys() method on an iterable will return a list of keys. So when you write:

for items in arg1.keys():

your for loop will iterate through ['Andrew Chalkley', 'Kenneth Love']. Accordingly, during the first iteration of that loop, items will have the value 'Andrew Chalkley'. Then when you do a for loop on 'Andrew Chalkley', it's going to iterate through the characters in 'Andrew Chalkley' and increment your counter every time you get a new character.

To correctly use the method you are trying to use, you would need to remember that your outer loop is going to be a series of keys. Then in your inner loop you can use that key to index back into the iterable to get the value. E.g.,:

for key in some_dictionary.keys():
    for element in some_dictionary[key]:
        print(element)

If this seems a bit long-winded, you're right. There is a better way, and that's to use .items() instead of .keys(). With .items() you get back a list of tuples where the first element in each tuple is the key and the second is the value. This means you can structure your for loop as follows:

for key, value in some_dictionary.items():
   print(key)
   print(value)

Hope this helps

Cheers

Alex