8/13


#1

Hi
This is the correct answer for this exercise. My question: I don’t understand how it knows that “food” is part of the 2 dictionaries-Prices and stock. IOW, how does it know that “banana” is food, “apple” is food etc.
I could not figure out how to ‘Print’ the individual food names, so I got the answer. I just don’t understand the answer.

‘’'
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]
’’’


#2

the keys for both dictionaries are the same. So it doesn’t matter which dictionary we loop, we can still simple print the key (product name, stored in the iterator variable)


#3

Thanks. My follow up question is even more basic than that.
How does the code know that “banana” is food, and that “apple” is food. Regardless if there is only 1 dictionary or 2.
I’m missing something.

John


#4

because you defined the loop iterator variable (food) in the loop, python will now assign the keys from the dictionary to the loop iterator.

so each iteration, food gets a value from the dictionary, the for .. in .. loop does this for you. The general syntax would be:

for key in dictionary:

or in case you have a list:

for value in list:

python is handling assign all the keys from dictionary (or values from list) to the loop iterator. Python does a lot of heavy lifting here


#5

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