Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

collections.OrderedDict

Maintains ordered key-value bindings and supports moving a key explicitly to either end.

Version: Python 3.14; repository image, production runtime not attested

Syntax

collections.OrderedDict([('a', 1), ('b', 2)])

Maintains ordered key-value bindings and supports moving a key explicitly to either end.

Equality between two ordered dictionaries takes key order into account even when their bindings match.

Use move_to_end(key) to make an existing key last, or pass last=False to make it first. A missing key raises KeyError. With another OrderedDict equality checks the order of pairs; comparison with an ordinary dict checks their bindings irrespective of order. Moving a changes the order of data alone, so its comparison with copy is False.

from collections import OrderedDict
d = OrderedDict(a=1, b=2)
d.move_to_end("b", last=False)
assert list(d) == ["b", "a"]
assert d != OrderedDict(a=1, b=2) and d == {"a": 1, "b": 2}
assert d.popitem(last=False) == ("b", 2)

Examples

import collections
data = collections.OrderedDict(a=1, b=2)
copy = data.copy()
data.move_to_end("a")
print(list(data), data == copy)

Result

['b', 'a'] False

Use move_to_end(key) to make an existing key last, or pass last=False to make it first. A missing key raises KeyError. With another OrderedDict equality checks the order of pairs; comparison with an ordinary dict checks their bindings irrespective of order. Moving a changes the order of data alone, so its comparison with copy is False.

Sources