collections.OrderedDict

suggest change

Since Python 3.7, a built-in dict keeps keys in insertion order:

>>> d = {'foo': 5, 'bar': 6}
>>> print(d)
{'foo': 5, 'bar': 6}
>>> d['baz'] = 7
>>> print(d)
{'foo': 5, 'bar': 6, 'baz': 7}
>>> d['foobar'] = 8
>>> print(d)
{'foo': 5, 'bar': 6, 'baz': 7, 'foobar': 8}

The order in which the keys appear is the order in which they are iterated over, for example in a for loop.

collections.OrderedDict also keeps that order. It still differs from dict: equality considers order, and it provides move_to_end(). Create one from a series of items (here, a list of key-value pairs):

from collections import OrderedDict
d = OrderedDict([('foo', 5), ('bar', 6)])
print(d)
# OrderedDict({'foo': 5, 'bar': 6})
d['baz'] = 7
print(d)
# OrderedDict({'foo': 5, 'bar': 6, 'baz': 7})
d['foobar'] = 8
print(d)
# OrderedDict({'foo': 5, 'bar': 6, 'baz': 7, 'foobar': 8})

Or we can create an empty OrderedDict and then add items:

o = OrderedDict()
o['key1'] = "value1"
o['key2'] = "value2"
print(o)
# OrderedDict({'key1': 'value1', 'key2': 'value2'})

Iterating through an OrderedDict allows key access in the order they were added.

What happens if we assign a new value to an existing key?

d['foo'] = 4
print(d)
# OrderedDict({'foo': 4, 'bar': 6, 'baz': 7, 'foobar': 8})

The key retains its original place in the OrderedDict.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents