all Python 3collectionsterm
collections.OrderedDict
ordereddict
A dictionary that remembers the insertion order. move_to_end() moves a key to the front or to the back.
Syntax
collections.OrderedDict([items])
odict.move_to_end(key, last=True)
Since Python 3.7 an ordinary dict already preserves insertion order, so OrderedDict is no longer about ordering as such but about three things: move_to_end(), popitem(last=False) to pop from the front, and order-sensitive equality — two OrderedDicts with the same pairs in a different sequence are unequal, while plain dicts would compare equal. The typical use today is an LRU cache: move a key to the end on access, evict from the front.
Examples
from collections import OrderedDict
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(od) # → OrderedDict({'a': 1, 'b': 2, 'c': 3}) — так repr выглядит с 3.12
od.move_to_end('a')
print(list(od)) # → ['b', 'c', 'a']
od.move_to_end('a', last=False)
print(list(od)) # → ['a', 'b', 'c'] — в начало
print(od.popitem(last=True)) # → ('c', 3) — последний
print(od.popitem(last=False)) # → ('a', 1) — первый
See also
Open in the full glossarydocs.python.orgReport an inaccuracy