OrderedDict is similar to dict with the capability to remember the order in which the keys are inserted. It is present in Collections module.
The OrderedDict is designed to offer better performance at reordering operations. This makes it useful in keeping track of recent accesses and thus used in LRU cache (a cache replacement algorithm).
Creating OrderedDict
OrderedDict can be created using built-in OrderedDict( ) function:
from collections import OrderedDictordDict = OrderedDict()
ordDict['alpha'] = 1
ordDict['beta'] = 2
ordDict['gamma'] = 3
ordDict['theta'] = 4
for key, val in ordDict.items():
print(key, val)
Observe the output, the insertion order is preserved
Update value of existing key
Updating the value of the existing key doesn’t affect its position
from collections import OrderedDict
ordDict = OrderedDict()
ordDict['alpha'] = 1
ordDict['beta'] = 2
ordDict['gamma'] = 3
ordDict['theta'] = 4
ordDict['beta'] = 3
for key, val in ordDict.items():
print(key, val)