14. Looping over a dictionary

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/en/courses/python-beginner-en-cxMGf/2/1?curriculum_id=4f89dab3d788890003000096#

<In what way does your code behave incorrectly? Include ALL error messages.>
My code seems to work correctly, the output on the console is what confusing me?

<What do you expect to happen instead?>
I think its suppose to print one value for each key but it prints all the values for each key?

```python

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

for key in d:
# Your code here!
print key, ‘apple’, ‘berry’, ‘cherry’
.

<do not remove the three backticks above>

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.

4 Likes

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].

2 Likes

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