8. Keeping Track of the Produce



price: 1.5
stock: 32
price: 3
stock: 15
price: 4
stock: 6
price: 2
stock: 0

My fruits resulted matching with its prices and stocks. But I type banana first in my dictionary. Why it resulted orange in the first line?

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15

for fruit in stock:
    print fruit
    print "price: %s" % prices[fruit]
    print "stock: %s" % stock[fruit]


Python dictionaries are implemented as hash tables, which are unordered. Therefore, when a program iterates through a Python dictionary, the order in which the items are encountered might not be the same as the order in which they are added to the dictionary. The items might not be encountered with the keys or values in sorted order, either.

See Wikipedia: Hash table.


is there a way to sort these buckets (fruit name, price, stock) to an order I wish?


You cannot sort the buckets themselves. However, you can save the keys in a sorted list, or within the list in any order that you want. Then use the list to access the dictionary. Following is an example ...

prices_list = sorted(prices.keys())

for key in prices_list:
    print key
    print "price: %s" % (prices[key])
    print "stock: %s" % (stock[key])


Your code worked and it sorted! :smile: I wonder why mine didn't, because I haven't added brackets () outside the value. What are the purpose of the brackets outside?

prices_list = sorted(prices.key())

for key in prices_list:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]


Could you post that statement exactly as you had it, so we can take a look at it?


ah sorry, it's here

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

i didn't put brackets() outside prices[key]. So the correct one would be like this (prices[key]). My question is what is the purpose of this brackets?


For those two statements, the brackets (parentheses) that you are referring to do not matter. That is because each statement only contains one value to be output. However, if you wanted to output more than one value in a statement, you would place the variables or expressions representing those values within parentheses, and separate them with commas, in order to contain them in a tuple.


now i see. thank you appy! :blush: