Sub topic 6
Insertion order and dictionary equality
This chapter assumes you can create dictionaries, read and change entries, and loop over keys(), values() and items(). It covers what order a dictionary keeps, which operations change that order, and why two dictionaries can be equal even when their order differs.
What the order guarantee means
A dictionary remembers the order in which its keys were first inserted. Iteration, list(d), keys(), values() and items() all follow that order. CPython 3.6 did this as an implementation detail. From Python 3.7 the language specification guarantees it, so you can rely on it.
This is not sorting. The dictionary does not arrange keys by value or alphabet. It only keeps the sequence in which they arrived.
Which operations move a key
Only inserting a new key adds it at the end. Updating an existing key keeps its position. Deleting a key and adding it again puts it at the end.
d = {}
d["b"] = 1
d["a"] = 2
d["c"] = 3
print(list(d)) # ['b', 'a', 'c']
d["b"] = 10 # update: position unchanged
print(list(d)) # ['b', 'a', 'c']
del d["b"]
d["b"] = 10 # new insertion: goes to the end
print(list(d)) # ['a', 'c', 'b']Working with the first and last entries
A dictionary has no integer index, so d[0] looks up the key 0. To get the first key, use next(iter(d)). To get the last, use reversed(), which works on dictionaries from Python 3.8. The popitem() method removes and returns the last pair, which is last-in, first-out.
d = {"a": 1, "c": 3, "b": 10}
print(next(iter(d))) # a
print(next(reversed(d))) # b
print(d.popitem()) # ('b', 10)
print(d) # {'a': 1, 'c': 3}Both next() calls raise an error on an empty dictionary (StopIteration), and popitem() raises KeyError. Check if d: first when the dictionary might be empty.
Equality ignores order
Two dictionaries are equal when they have the same keys and each key maps to an equal value. The order of insertion plays no part in this.
x = {"a": 1, "b": 2}
y = {"b": 2, "a": 1}
print(x == y) # True
print(list(x) == list(y)) # False
print(list(x.items()) == list(y.items())) # FalseIf order matters to your program, compare the items() lists as shown on the last line. Comparing dictionaries directly will not detect a difference in order.
Values are compared with ==, so {"n": 1} == {"n": 1.0} is True. The same rule applies to keys. Because 1 == 1.0 and hash(1) == hash(1.0), they count as the same key.
d = {1: "int"}
d[1.0] = "float"
print(d) # {1: 'float'}The key stays as the original 1, and only the value was replaced.
OrderedDict compares order
collections.OrderedDict is a dictionary subclass whose equality with another OrderedDict takes order into account. Comparing it with a plain dict still ignores order.
from collections import OrderedDict
x = {"a": 1, "b": 2}
y = {"b": 2, "a": 1}
print(OrderedDict(x) == OrderedDict(y)) # False
print(OrderedDict(x) == y) # TrueToday you rarely need OrderedDict. It remains useful when order-sensitive equality is part of the meaning of your data, or when you need move_to_end() to reposition a key without deleting it.
Common mistakes
- Expecting an update to move a key to the end. It does not. Delete the key first, or use
OrderedDict.move_to_end(). - Using
d[0]to get the first entry. This is a key lookup and raisesKeyErrorunless0is a key. - Assuming a
sethas the same guarantee. Sets do not preserve insertion order. - Writing code for Python 3.5 or earlier, where order was not preserved.
Exercise
Given a = {"x": 1, "y": 2} and b = {"y": 2, "x": 1}, what do a == b and list(a) == list(b) print? Then, starting from a, what is list(a) after you run del a["x"] followed by a["x"] = 1?
Show answer
a == b prints True because dictionary equality ignores order. list(a) == list(b) prints False because the key orders are ['x', 'y'] and ['y', 'x']. After deleting "x" and adding it again, it is a new insertion at the end, so list(a) is ['y', 'x'].