Introduction
OrderedDict maintains insertion order, useful when order matters and you need dict features.
OrderedDict Basics
from collections import OrderedDict
od = OrderedDict()
od["a"] = 1
od["b"] = 2
od["c"] = 3
# Preserves insertion order
for k, v in od.items():
print(k, v)
Move to End/Start
od = OrderedDict({"a": 1, "b": 2, "c": 3})
od.move_to_end("a") # Move 'a' to end
od.move_to_end("a", last=False) # Move to start
# Reverse iteration
for k in reversed(od):
print(k)
Comparison
from collections import OrderedDict
od1 = OrderedDict({"a": 1, "b": 2})
od2 = OrderedDict({"b": 2, "a": 1})
d = {"a": 1, "b": 2}
# OrderedDict considers order
print(od1 == od2) # False
print(dict(od1) == d) # True (regular dict, Python 3.7+)
Practice Problems
- Create LRU cache with OrderedDict
- Track access order of items
- Implement most recently used tracking
- Reorder dictionary by values
- Serialize OrderedDict to JSON