Python Ordered Dictionaries

We had already discussed that the elements of a dictionary are not ordered. It means the elements are not stored into the same order as they were entered into the dictionary. Sometimes this becomes a problem.

Ordered dictionary

An ordered dictionary is a dictionary but it will keep the order of the elements. The elements are stored and maintained in the same order as they were entered into the ordered dictionary. We can create an ordered dictionary using the OrderedDict() method of 'collections' module.

So, first we should import this method from collections module, as: from collections import OrderedDict

Once this is done, we can create an ordered dictionary with the name 'd' as:

d = OrderedDict()

Ordered Dictionaries example:

A Python program to create a dictionary that does not change the order of elements.

CopiedCopy Code

from collections import OrderedDict 
d = OrderedDict()
d[10] = 'A' 
d[11] = 'B' 
d[12] = 'C' 
d[13] = 'D' 
for i, j in d.items(): 
   print(i, j)