Looping over a dictionary issue


#1



I thought I had this all worked out, but it's not printing out what I expected (or what the program wants me to do)

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


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


for key in d:
    if d[key] == 'berry':
        print d, d[key]

For some reason it prints out {'a': 'apple', 'c': 'cherry', 'b': 'berry'} berry
I would expect it to only print out b berry. Can anyone explain what i'm doing wrong?


#2

After looking at many other posts in this form (specfically https://discuss.codecademy.com/t/looping-over-a-dictionary/28022/2), I realized that I should be using the if statement of "print key, d[key]". However, the program is still telling me my code didn't print b berry (which it most certainly did!). does anyone have any suggestions?


#3

Hi @maximon6682,

The message is giving incorrect information. You did display b berry.

To pass, just remove this if block header ...

    if d[key] == 'berry':

You need to display each of the keys along with their associated values.


#4

Thanks @appylpye! I believe I was mis-interpreting the instructions; I thought I was only supposed to have an output of b berry. it was asking me to output all three dict keys and values.


#5

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