'Keeping Track of the Produce' - Unordered Dictionary: Can I order?


#1


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


I'm curious how the order of keys printed is determined. Is it 'random' as suggested earlier in this lesson? I've tried cutting and pasting my prices and stocks in different orders, but it always prints the price & stock for "Orange" first. Also, it seems to be sorting in descending order by stock. Just a coincidence?


stock = {
    "Banana" : 6, 
    "Apple" : 0,
    "Pear" : 15,
    "Orange" : 32
}

prices = {
    "Banana" : 4, 
    "Apple" : 2,
    "Pear" : 3,
    "Orange" : 1.5, 
}

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


#2

Hi @methodsurfer83618

This is a great question. I have searched around and found an interesting answer there: http://stackoverflow.com/questions/14445667/what-is-the-order-of-looping-for-loop-in-python-dictionary.

To summarize what it says, basically, python dictionaries basically doesn't have any order. However, you can specify an order to loop on. In order to do that, you can use the sorted function as suggested:

for key in sorted(array):
  print key

Hope this answered your question! :wink:


#3

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