Print dictionary values


#1

for this set of 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]

I am failing to understand how the last two lines produce the output…why is it key and not value?

how print “price: %s” % prices[key]
print “stock: %s” % stock[key]


#2

what do you mean? this two lines:

  print "price: %s" % prices[key]
  print "stock: %s" % stock[key]

we use the keys to get the values, so that we may print the values.

we can get the values from a dictionary using the key + square brackets, like you do


#3

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