Dictionary keys and values



The code works. What I don't understand is this: for key in d references the key of every entry in the dictionary. Why does d[key] reference the value? is [key] always just the way to call the value associated with a key?

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

for key in d:
    # Your code here!
    print key, d[key]


well as you can see:

for key in d:
    # Your code here!
    print key

key contains the keys from your dictionary, and it is called key because you called it as such in the declaration of your for loop. Then you can [key] to get the values


Thanks. One of the things I'm struggling to differentiate between is places where I declare the name of something, versus times when I'm calling on a structured terminology.

I thought in this case key was an already defined function I was invoking, not a variable I was naming.