OrderedDict

Contents

OrderedDict#

collections.OrderedDict is the pre-3.7 ordered dict. The plain dict has been insertion-ordered since 3.7, so most operators reach for dict instead. OrderedDict is still useful for the two things dict does not provide: move_to_end and order-aware equality.

from collections import OrderedDict
od = OrderedDict()
od["a"] = 1; od["b"] = 2
od.move_to_end("a")           # rotate "a" to last
od.move_to_end("b", last=False)  # rotate "b" to first

OrderedDict([("a", 1), ("b", 2)]) == OrderedDict([("b", 2), ("a", 1)])
# False --- order matters in OrderedDict equality

LRU caches and “least recently used” eviction are the canonical use case for move_to_end; functools.lru_cache is built on top of OrderedDict.

References#