8. Keeping Track of the Produce


#1



https://www.codecademy.com/courses/python-beginner-en-IZ9Ra/1/3?curriculum_id=4f89dab3d788890003000096


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


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]


#2

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.


#3

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


#4

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])

#5

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]

#6

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


#7

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?


#8

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.


#9

now i see. thank you appy! :blush:


#10