PythonMastery

OrderedDict in Python

Normal dicts keep insertion order since Python 3.7. What OrderedDict still adds: move_to_end(), popitem(last=False) and order-aware ==.

Since Python 3.7, a normal dictionary keeps keys in the order you added them. So you rarely need OrderedDict just to keep order. It is still useful for its extra methods, which let you move keys to either end.

The program

python
from collections import OrderedDict

steps = OrderedDict()
steps["wash"] = 10
steps["chop"] = 5
steps["cook"] = 20

for name, minutes in steps.items():
    print(name, minutes)

steps.move_to_end("wash")
print(list(steps))

steps.move_to_end("cook", last=False)
print(list(steps))

print(steps.popitem(last=False))
print(list(steps))
output
wash 10
chop 5
cook 20
['chop', 'cook', 'wash']
['cook', 'chop', 'wash']
('cook', 20)
['chop', 'wash']

How it works

Order and equality

python
from collections import OrderedDict

a = {"x": 1, "y": 2}
b = {"y": 2, "x": 1}
print(a == b)

oa = OrderedDict(a)
ob = OrderedDict(b)
print(oa == ob)
output
True
False

Two normal dictionaries are equal when they have the same keys and values, in any order. Two OrderedDict objects are equal only if the order is also the same.

Learn the idea: collections: The Stdlib's Hidden Power, Dictionaries