Understanding the For Loop with Dictionary Keys



Hi there,

I just finished the exercise "8. Keep Track of the Produce" in the "A Day at the Supermarket" section and my code works fine, and I can see what it's doing but I don't understand it.

Inside the For Loop, 'key' is the key from the dictionary (so "banana" for instance).

Then it prints "banana" with 'print key'.

Then it prints the value associated with "banana" in the price dictionary with 'print "price: %s" % prices[key]', rather than just printing banana? I'd expect something like this;

price: banana
stock: banana

What am I missing? :sweat:

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15

for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]


key         => key name, "banana"
prices[key] => value associated with 'banana' key, namely, `4`

The subscript is the key name, the identifier object[key] is the value.


I think I understand, thanks very much!