Reorder Entries with OrderedDict
Core idea
A regular dict preserves insertion order. OrderedDict adds operations for frequent reordering: move_to_end(key, last=True) moves a key to the right end, or to the left when last=False. popitem(last=False) removes the first pair.
from collections import OrderedDictrecent = OrderedDict([("a", 1), ("b", 2), ("c", 3)])recent.move_to_end("a")print(list(recent))The entry keeps its value but becomes last.
Evict the oldest entry
from collections import OrderedDictcache = OrderedDict([("x", 4), ("y", 5)])cache.move_to_end("y", last=False)print(cache.popitem(last=False))print(list(cache))Moving to the front changes which entry is removed first.
Compare two orders
from collections import OrderedDicta = OrderedDict([("x", 1), ("y", 2)])b = OrderedDict([("y", 2), ("x", 1)])print(a == b, a == dict(b))Two OrderedDict instances compare order as well as contents; comparison with a regular dict ignores order.
Common mistake
Assigning to an existing key does not move it to the end. Use move_to_end explicitly. A missing key raises KeyError.
Practice
Build a three-entry recent-use list; move the first key to the end and remove the oldest remaining key.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Explicit ordering
Check your understanding of ordereddict.
What is printed?
from collections import OrderedDictd = OrderedDict(a=1, b=2)d.move_to_end("a")print(list(d))What is printed?
from collections import OrderedDictd = OrderedDict(a=1, b=2)print(d.popitem(last=False))What is printed?
from collections import OrderedDictprint(OrderedDict(a=1,b=2) == OrderedDict(b=2,a=1))What is an advantage of OrderedDict over dict?