"Something of Value" question

in this code:

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]

total = 0
for n in prices:
total = total + prices[n] * stock[n]
print total

i get this as an aswer:

orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0
117.0

But how does the “for n in prices:” understand the “stock”?

how does in understand i am looking for the n in stock since its not defined?

To preserve code formatting in forum posts, see: [How to] Format code in posts

prices and stock are dictionaries. Their elements are key-value pairs.

In a for-in loop iterating over a dictionary, in each iteration a key of the dictionary will be assigned to the loop variable. The name of the loop variable is our choice (provided we don’t pick reserved keywords such as def, yield, break, else etc., and we don’t choose invalid identifiers such as 3i, n@t etc.). However, it is a good idea to pick variable names which contribute to better readability.

Both the for key in prices: and the for n in prices: loops are the same except for the loop variable name. In each iteration of the loop, one of the keys such as "banana", "apple" etc. of the prices dictionary will be assigned to the loop variable. In the first loop, the strings will be assigned to the loop variable key. In the second loop, the strings will be assigned to the loop variable n. The bracket notation prices[n] or stock[n] will allow you to access the value paired with the key. e.g. If the current iteration has assigned the string "apple" to the loop variable n, then prices[n] and stock[n] will be interpreted as prices["apple"] and stock["apple"] allowing you to access the values 2 and 0 respectively.

2 Likes