14. Looping over a dictionary


#1



https://www.codecademy.com/en/courses/python-beginner-en-cxMGf/2/1?curriculum_id=4f89dab3d788890003000096#


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


#2

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.


#3

Thanks, it's working correctly now.


#4

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


#5

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