collections.OrderedDict
suggest changeThe order of keys in Python dictionaries is arbitrary: they are not governed by the order in which you add them.
For example:
>>> d = {'foo': 5, 'bar': 6}
>>> print(d)
{'foo': 5, 'bar': 6}
>>> d['baz'] = 7
>>> print(a)
{'baz': 7, 'foo': 5, 'bar': 6}
>>> d['foobar'] = 8
>>> print(a)
{'baz': 7, 'foo': 5, 'bar': 6, 'foobar': 8}
(The arbitrary ordering implied above means that you may get different results with the above code to that shown here.)
The order in which the keys appear is the order which they would be iterated over, e.g. using a `for` loop.
The collections.OrderedDict
class provides dictionary objects that retain the order of keys. OrderedDict
can be created as shown below with a series of ordered items (here, a list of tuple 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
.