Keeping track of products


Hi, I don’r understand something about the for loop. I have a code and it works so I can go to the next exercise but there is something I don’t get. This is my code:

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

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

for food in prices:
print food
print “price: %s” % prices[food]
print “stock: %s” % stock[food]

and this is my output:

price: 1.5
stock: 32
price: 3
stock: 15
price: 4
stock: 6
price: 2
stock: 0

My question is: How does the for loop run through the prices dictionary AND the stock dictionary. When it is stated like: for food in prices. Shouldn’t it contain something about the stock dictionary too? I don’t get it. Please help, thanks!


it doesn’t. But the keys in both the dictionaries are the same, so it doesn’t matter which of the two dictionaries you loop through, you get the key which you can use to get values from both dictionaries.


Aaaah now I get it. So when I have two dictionaries with different key’s and I want to print all of the keys from both dictionaries I should make two for loops?


yes, exactly :slight_smile:


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