14. Looping over a dictionary



My code seems to work correctly, the output on the console is what confusing me?

I think its suppose to print one value for each key but it prints all the values for each key?

d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}

for key in d:
    # Your code here!
    print key, 'apple', 'berry', 'cherry'  


Hi, @mondli_kenneth ,

The instructions ask you to do this ...

On line 5, print the key, followed by a space, followed by the value associated with that key.

This portion of your statement inside the for loop takes care of the key ...

print key

... but you have also included this in your print statement ...

'apple', 'berry', 'cherry'

... so every time the loop iterates, you will also output those strings. Instead of those strings, you need to output the value associated with the key. Since the key is referenced by the variable, key, in your for loop, you can access the value associated with that key with the expression d[key]. Replace the three strings with that expression in the print statement.


Thanks, it's working correctly now.


Hi there, you could make it more easier to read and more logical with using print key, d[key].


This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.