An OrderedDict
is a data structure from the collections module that stores an ordered mapping of keys to values. By contrast, elements in a regular dictionary has no order. This makes an OrderedDict
useful when the order in which you insert items into the dictionary is important and needs to be maintained.
The basic functionality of an OrderedDict
is similar to that of the standard dictionary, in fact, OrderedDict
class is a subclass of the dict
type.
OrderedDict
is a subclass of dict
from collections import OrderedDict
print(issubclass(OrderedDict, dict))
The only difference is that the order in which items are entered into an OrderedDict
is maintained. This ensures that when iterating over the dictionary, the keys will come out in the same order used when they were added.
Working with OrderedDicts
As we have already said, OrderedDicts work similarly to the standard dicts except in cases where the order of element is important such as in comparison operations.
To instantiate an OrderedDict
we use a syntax similar to that of dicts.
OrderedDict(mapping = None, iterable = None, **kwargs)
mapping |
Used when we are creating an OrderedDict from a mapping such as a regular dictionary |
iterable |
Used when we are creating an OrderedDict from an iterable containing key-value pairs |
**kwargs |
Used when we are creating the OrderedDict using the key = value syntax. |
Create an OrderedDict using the key = value syntax
from collections import OrderedDict
d = OrderedDict(one = 1, two = 2, three = 3, four = 4)
print(d, '\n')
for k, v in d.items():
print(k, v)
Create an OrderedDict
from key-value pairs
from collections import OrderedDict
d = OrderedDict([('Tokyo', 'Japan'), ('Stockholm', 'Sweden'), ('Helsinki', 'Finland' ), ('Nairobi', 'Kenya'), ('Manilla', 'Philippines')])
print(d, '\n')
for k, v in d.items():
print(k, v)
Comparison Operation on OrderedDicts
Elements in a regular dictionary have no order, this means that two dictionaries with same set of elements are always regarded as equal.
d1 = {'one': 1, 'two': 2, 'three': 3}
d2 = {'three': 3, 'one': 1, 'two': 2}
print(d1 == d2)
In OrderedDict
, as you might expect, the order is important when comparison operations are carried out.
from collections import OrderedDict
d1 = OrderedDict(one = 1, two = 2, three = 3)
d2 = OrderedDict(three = 3, one = 1, two = 2)
print(d1 == d2)
Two OrderedDict
objects will only be consindered equal if they have the same set of elements and the elements appear in the same order in both dictionaries.