Why is my dictionary sorting?


#1




In printout I get an item order I do not expect:
I get
orange price: 1.5 stock: 32
pear price: 3 stock: 15
banana price: 4 stock: 6
apple price: 2 stock: 40

I would have thought that without a sort function applied I should have seen the following returned, mimicing the list order in my dictionary:
banana price: 4 stock: 6
apple price: 2 stock: 40
orange price: 1.5 stock: 32
pear price: 3 stock: 15

Why is this happening, and how would I stop it?


price ={}
stock = {}
price={
'banana':4,
'apple':2,
'orange':1.5,
'pear':3
}
stock={
'banana':6,
'apple':40,
'orange':32,
'pear':15
}
for item in stock:
    print item,
    print 'price: '+ str(price[item]),
    print 'stock: '+ str(stock[item])


#2

@csswhiz79288 ,

The dict type is technically a hash table, which is unordered, The main reason for lack of ordering is that the keys in a given dict can vary among many different types, making it challenging to define a sorting order.

If you would like to control the order in which you access the items in a dict, you can save the keys in a list, and sort the list or do anything else you want to order the keys. Then loop through the list, using the items as keys to access the dict.


#3

Thank you.

So the only way I can expect to get a specific order on a dictionary is to run a sort on it - after generation or alteration.


#4

Our posts crossed; see above ...

We cannot literally sort a dict, but can sort a list of its keys.


#5

Got it, thanks.

Concise and clear answer :+1:


#6

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