How to Create Ordered Dictionary in Python?

Dictionary in Python is one of the most useful core data structures in Python. Sometimes, you may want to create a dictionary and also maintain the order of items you inserted when you are iterating the keys.

Python’s collections module has OrderedDict that lets you create a ordered dictionary. Let us see an example of ordered dictionary and how it differs from regular dictionary in Python.

import collections

Create Ordered Dictionary

We can create ordered dictionary using OrderedDict function in collections.

ordered_d = collections.OrderedDict(one=1, two=2, three=3)

Ordered dictionary preserves the insertion order.

ordered_d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

We can iterate through the dictionary items and see that the order is preserved.

for k,v in ordered_d.items():
    print(k,v)

one 1
two 2
three 3

If you are using Python version 3.6+, the core dictionary data structure in Python also preserves the insertion order. Python documentation claims that

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).