0
>>> dict1 = {'1':'aaa' , '2':'bbb' , '5':'fff' , '10':'zzz'}
>>> dict1
{'1': 'aaa', '10': 'zzz', '2': 'bbb', '5': 'fff'}

>>> dict3 = {'1':'aaa' , '2':'bbb' , '11' : 'hhh' , '5':'fff' , '7' : 'ggg' , '10':'zzz'}
>>> dict3
{'11': 'hhh', '10': 'zzz', '1': 'aaa', '2': 'bbb', '5': 'fff', '7': 'ggg'}

In what manner/algorithm, the dictionary is maintaining the sorting of keys/values, BY DEFAULT??

Deep LF
  • 199
  • 1
  • 12
  • 2
    It is not maintaining the order. – David Zwicker Oct 22 '13 at 12:32
  • possible duplicate of [Why is python ordering my dictionary like so?](http://stackoverflow.com/questions/526125/why-is-python-ordering-my-dictionary-like-so) – kjhughes Oct 22 '13 at 12:34
  • then why '10':'zzz' is coming before '2' & '5' , though I entered tht key/value in the last place? – Deep LF Oct 22 '13 at 12:34
  • @DeepLF As a consequence of the internals of a python dictionary in this specific case. You might construct other examples which will look different. Take a look at e.g. http://www.laurentluce.com/posts/python-dictionary-implementation/ on how dictionaries might be stored in python. For practical usage, you need to consider the keys to not be in any particular order. – nos Oct 22 '13 at 12:37

1 Answers1

2

Python dictionaries are not ordered. You can use collections.OrderedDict for a dict-like object that is ordered by insertion order.

When you print a dict or iterate through the keys, the output is in an arbitrary order that's stable as long as the dictionary isn't changed.

Wooble
  • 87,717
  • 12
  • 108
  • 131