So far, the dictionaries that we have created do not maintain the insertion order of the key-value pairs that are added. Ordered dictionaries are dictionaries that maintain the insertion order of keys. This means that when you are iterating through them, you will always access the keys in the order in which they were inserted.
The OrderedDict class is a dict subclass defined in the collections package that Python ships with. We will use ordered dictionaries when it is vitally important to store and retrieve data in a predictable order; for example, when reading database entries.
The following section will describe how to work with them.
Creating an ordered dictionary is as easy as creating an instance of the OrderedDict class and passing in key-value pairs:
>>> from collections import OrderedDict >>> a = OrderedDict(name="Zeus", role="god") >>> a OrderedDict([('name', 'Zeus'), ('role', 'god')])
Everything about OrderedDict, except for it maintaining...