0
>>> basket = {'fruit' : 'apple','veg' : 'potato', 'grain' : 'rice', 'liquor' : 'wine'}
>>> for k,v in basket.iteritems():
...     print k,v
... 
veg potato
liquor wine
fruit apple
grain rice
>>> 

As can be seen from the above example, the key-value pair are not printed from left to right or from right to left.

To get a sorted result, I used

>>> basket = {'fruit' : 'apple','veg' : 'potato', 'grain' : 'rice', 'liquor' : 'wine'}
>>> for k,v in sorted(basket.iteritems()):
...     print k,v
... 
fruit apple
grain rice
liquor wine
veg potato
>>> 

When I try to get the indices of the key-value pairs, I get

>>> basket = {'fruit' : 'apple','veg' : 'potato', 'grain' : 'rice', 'liquor' : 'wine'}
>>> for k,v in enumerate(basket.iteritems()):
...     print k,v
... 
0 ('veg', 'potato')
1 ('liquor', 'wine')
2 ('fruit', 'apple')
3 ('grain', 'rice')
>>> 

Why does this happen? How can I print the key-value pairs as it appears in the dictionary definition, from left to right?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Goku__
  • 940
  • 1
  • 12
  • 25

1 Answers1

1

If you've ever made a hash table, you know that order is not necessary to store.

In fact, it's extra work.

If you want to keep the order of inserted items, you can use collections.OrderedDict, which does just that.

Paul Draper
  • 78,542
  • 46
  • 206
  • 285