Reading Time: 1 minutes
Maintaining order in Dictionaries in Python
Maintaining order in Dictionaries: The regular behaviour of Python dictionaries is such that, the order in which the key-value pairs are declared is not necessarily the order in which they are stored in memory. For example:
Maintaining order in Dictionaries
>>> normalDictionary = {2: 'two', 3: 'three', 1: 'one'} >>> normalDictionary {1: 'one', 2: 'two', 3: 'three'}
If you wish to have a dictionary which maintains this order, you can use the OrderedDict class of standard library collections.
>>> import collections >>> orderedDictionary = collections.OrderedDict({2: 'two', 3: 'three', 1: 'one'}) >>> orderedDictionary OrderedDict([(1, 'one'), (2, 'two'), (3, 'three')]) >>> dict(orderedDictionary) {1: 'one', 2: 'two', 3: 'three'}
This class was introduced in version 2.7. If you want similar functionality in older versions, I suggest you look at this page.