-3
prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}
stock = {
    "banana": 6,
    "apple" : 0,
    "orange": 32,
    "pear": 15
}

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

The outout of the following code gives the following output

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

I want to ask why is it displayed in this way (in sorted order) . Isn't banana should come first , then apple , orange and pear ?

Burger King
  • 2,845
  • 3
  • 18
  • 44

4 Answers4

1

It's not sorted. You use a dictionary to store your data. Standard dictionaries in Python are unordered. They basically are a hashmap of keys connected to values. The order you see is the order of keys in the dict's hashmap.

Eli Korvigo
  • 9,646
  • 6
  • 46
  • 71
1

an unordered dictionary is most probably implemented as a hash table (in fact, the Python documentation states this outright) where the order of elements is well-defined but not immediately obvious. Your observations match the rules of a hash table perfectly: apparent arbitrary, but constant order.

Thanks to @konrad-rudolph

backtrack
  • 7,822
  • 5
  • 48
  • 98
1

dict doesn't guarantee sorting, it is basically a Hash Table.

Order is based on hash() function, you may check this in interpreter:

>>> hash('orange') < hash('pear')
True

To print keys in really sorted order, use OrderedDict or apply sorted() while iterating keys:

for item in sorted(prices.keys()):
     ...
myaut
  • 10,658
  • 2
  • 26
  • 59
0

Python Dict has no order.So you can use OrderedDict

from collections import OrderedDict
for i, j in  OrderedDict(sorted(prices.items(), key=lambda x:x[1])).items():
    print i, j

orange 1.5
apple 2
pear 3
banana 4
itzMEonTV
  • 18,806
  • 3
  • 37
  • 48