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
- Items come out in the order they were added, the same as a normal dictionary.
move_to_end(key)moves a key to the end. Withlast=False, it moves the key to the start.popitem(last=False)removes and returns the first item. A normal dictionary'spopitem()can only remove the last one.- These two methods make
OrderedDicta simple way to build a queue of keys, or a cache that removes the oldest entry first.
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.