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 (Retired) Dictionaries Dictionary Iteration

igsm '
igsm '
10,440 Points

Function returns only 1st item of dictionary. How to iterate through all keys and values in function?

Hey Kenneth Love

I play with functions and dictionaries and faced a problem. I want to print in the string all the content of dictionary but it seems like it outputs only first item of the dictionary.

def f():
    fixtures = {'Item1': ('a', 'b', ('', '')),
                'Item2': ('c', 'd', ('', ''))}
    for keys, values in fixtures.iteritems():
        return '{} - {} and {}    {} - {}'.format(
        keys, values[0], values[1],values[2][0], values[2][1])

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

Running in ipython, I noticed two errors. (I added extra data for testing):

  • 'dict' object has no attribute 'iteritems'. Change to items()
  • return stops the loop on the first interation. Replace with print()
In [8]: def f():
        fixtures = {'Item1': ('a', 'b', ('x', 'y')),
                    'Item2': ('c', 'd', ('v', 'w'))}
        for keys, values in fixtures.items():
                print('{} - {} and {}    {} - {}'.format(
                keys, values[0], values[1],values[2][0], values[2][1]))
   ...:         

In [9]: f()
Item2 - c and d    v - w
Item1 - a and b    x - y