Understanding the For Loop with Dictionary Keys


#1

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

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;

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

Thanks!


#2
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.


#3

I think I understand, thanks very much!