0

Why is it that the print key yields a list of the names of the fruits but print prices[key] yields the numbers after each fruit? Should key print the same thing (the fruit names)?

Here's the 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]

Here is the result

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

TKW
  • 27
  • 4
  • Key and prices[key] are not the same thing, why are you treating them as such? Google Python dictionary. – kabanus Jul 09 '17 at 19:07
  • 1
    Possible duplicate of [Why does this python dictionary get created out of order using setdefault()?](https://stackoverflow.com/questions/11784860/why-does-this-python-dictionary-get-created-out-of-order-using-setdefault) – idjaw Jul 09 '17 at 19:08

3 Answers3

1

The statement for key in prices gives you the keys of the dictionary. The statement print prices[key] gives you the value associated with key.

aquil.abdullah
  • 3,059
  • 3
  • 21
  • 40
  • So if I had just written:`print "price: %s" % prices[key] print "stock: %s" % stock[key]`Then I would have gotten a list of the fruits in each dictionary? – TKW Jul 09 '17 at 19:34
  • No, you would have gotten a list of prices and the and the number of each fruit in stock. When you do a `for thing in dictionary` thing will always be a key. What is it the actual outcome that you are trying to achieve? – aquil.abdullah Jul 10 '17 at 12:05
0

NVM what I previously wrote (misread question). Like the other post states you are printing the key of the dictionary with the statement print key and then you are printing the value that is associated w/ the key when you do print price[key] so to print all in one like you can do the following

for key in prices:
    print "item: ", key, " price: ", prices[key], " stock: " stock[key]

The above will throw a key error if it does not exist in the stock dictionary FYI.

Here is a solid answer to a similar question https://stackoverflow.com/a/5905166/3990806

Adam
  • 3,992
  • 2
  • 19
  • 39
0
for key in prices:

is equivalent to:

for key in prices.keys():

That is, you are iterating over the keys of a dictionary. prices[key] is retrieving a value in the dictionary associated with the corresponding key. That is,

prices[key]

is equivalent to

prices.values()[prices.keys().index(key)]

If you want to get a list of values in a dictionary use values() method and if you want to get a list of keys (such as fruit names in your dictionaries) use the keys() method.

AGN Gazer
  • 8,025
  • 2
  • 27
  • 45