Keeping track of products


#1

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:

orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
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!


#2

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.


#3

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?


#4

yes, exactly :slight_smile:


#5

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