Sub topic 6
Insertion order and dictionary equality
This chapter assumes you can create dictionaries, read and change entries, and loop over them with keys(), values() and items(). It also assumes you know the difference between mutable and immutable objects. Here you will learn what order a dictionary keeps, what that order does and does not affect, and how Python decides whether two dictionaries are equal.
What insertion order guarantees
A dictionary remembers the order in which its keys were first added. Iterating over it, and over its views, yields keys in that order.
config = {}
config["host"] = "localhost"
config["port"] = 8080
config["debug"] = True
print(list(config)) # ['host', 'port', 'debug']
print(list(config.values())) # ['localhost', 8080, True]
print(list(config.items())) # [('host', 'localhost'), ('port', 8080), ('debug', True)]In CPython 3.6 this was an implementation detail. Since Python 3.7 it is part of the language specification, so you can rely on it in any conforming implementation. Code written for Python 3.6 or earlier should not assume it.
The order is the order of first insertion. The rules for later operations are:
| Operation | Effect on order | Column |
|---|---|---|
| Add a new key | The key goes at the end | |
| Assign to an existing key | The key keeps its position, only the value changes | |
| Delete a key, then add it again | The key goes at the end | |
| `pop()` or `del` of a key | The remaining keys keep their relative order | |
| `update()` or `\ | ` with a new key | New keys are appended in the order they arrive |
d = {"a": 1, "b": 2, "c": 3}
d["a"] = 100 # existing key: position unchanged
print(list(d)) # ['a', 'b', 'c']
del d["a"]
d["a"] = 1 # re-added: now last
print(list(d)) # ['b', 'c', 'a']A common surprise is that reassigning a key does not move it to the end. If you want that behavior, remove the key first.
d = {"a": 1, "b": 2, "c": 3}
d["a"] = d.pop("a") + 10
print(d) # {'b': 2, 'c': 3, 'a': 11}Order in merged dictionaries
When you merge, keys from the left operand come first. A key that appears in both keeps its position from the left operand, but takes its value from the right.
left = {"x": 1, "y": 2}
right = {"y": 20, "z": 30}
print(left | right) # {'x': 1, 'y': 20, 'z': 30}
print(right | left) # {'y': 2, 'z': 30, 'x': 1}Last item and reversal
Because the order is defined, two features follow from it. popitem() removes and returns the most recently inserted pair (last in, first out). reversed() works on dictionaries and views from Python 3.8.
d = {"a": 1, "b": 2, "c": 3}
print(d.popitem()) # ('c', 3)
print(list(reversed(d))) # ['b', 'a']Calling popitem() on an empty dictionary raises KeyError.
Order is not part of equality
Two dictionaries are equal when they have the same set of keys and each key maps to an equal value. The order of insertion is ignored.
a = {"x": 1, "y": 2}
b = {"y": 2, "x": 1}
print(a == b) # True
print(list(a) == list(b)) # False
print(a != b) # FalseThe second line shows the distinction. The dictionaries are equal, yet iterating over them gives different sequences. If your code depends on order, == will not tell you that two dictionaries differ in order.
Equality compares values with ==, so it recurses into nested structures.
p = {"name": "Ada", "tags": ["a", "b"]}
q = {"tags": ["a", "b"], "name": "Ada"}
print(p == q) # True
r = {"name": "Ada", "tags": ["b", "a"]}
print(p == r) # False, because lists compare in orderHere the dictionaries ignore order, but the lists inside them do not.
Keys are matched with == and hash(), so keys that compare equal are the same key, even if their types differ.
d = {1: "int", 1.0: "float", True: "bool"}
print(d) # {1: 'bool'}
print(len(d)) # 11, 1.0 and True are equal and have the same hash. The second and third assignments therefore replace the value of the first key. The key object stays the original 1, while the value is the latest one. This is a real source of bugs when you mix numbers and booleans in keys.
Comparing with `OrderedDict`
The collections.OrderedDict class predates guaranteed ordering. It still differs from dict in one way that matters here: equality between two OrderedDict objects is order-sensitive.
from collections import OrderedDict
a = OrderedDict([("x", 1), ("y", 2)])
b = OrderedDict([("y", 2), ("x", 1)])
print(a == b) # False
print(dict(a) == dict(b)) # True
print(a == {"y": 2, "x": 1}) # TrueWhen one side is an OrderedDict and the other is a plain dict, the comparison ignores order. OrderedDict also provides move_to_end(), which is handy for implementing caches that track recent use.
from collections import OrderedDict
cache = OrderedDict(a=1, b=2, c=3)
cache.move_to_end("a")
print(list(cache)) # ['b', 'c', 'a']
cache.move_to_end("c", last=False)
print(list(cache)) # ['c', 'b', 'a']Use a plain dict by default. Reach for OrderedDict when you need order-sensitive equality or move_to_end().
Comparing order explicitly
If you need to check that two dictionaries have the same contents in the same order, compare their item sequences.
a = {"x": 1, "y": 2}
b = {"y": 2, "x": 1}
print(a == b) # True
print(list(a.items()) == list(b.items())) # FalseViews and set-like comparison
The keys() and items() views support set operations, and comparing them is also order-independent. The values() view does not behave like a set, because values can repeat and may be unhashable.
a = {"x": 1, "y": 2}
b = {"y": 2, "z": 3}
print(a.keys() & b.keys()) # {'y'}
print(a.keys() - b.keys()) # {'x'}
print(a.items() & b.items()) # {('y', 2)}
print(a.keys() == {"y", "x"}) # TrueThe result of a set operation on views is a real set, so it has no order you should rely on.
Diagram: what changes the order
Edge cases and gotchas
- Order depends on first insertion, not on value. Updating values never reorders keys.
- Equal dictionaries can print differently.
print(a)andprint(b)may show different text even whena == bisTrue. Do not compare string forms of dictionaries to test equality. - JSON and serialization.
json.dumpswrites keys in insertion order. Two equal dictionaries can therefore produce different JSON text. Usesort_keys=Truewhen you need a stable form, for example for hashing or comparing files. - Sets are different. A
sethas no guaranteed order. Do not assume that a set of keys iterates in the same way as the dictionary. - Floating point values.
float("nan")is not equal to itself, so a dictionary holdingnanas a value does not always compare equal to itself by value. Python first checks identity, so the samenanobject compares equal, but two separatenanobjects do not.
nan = float("nan")
print({"v": nan} == {"v": nan}) # True, same object
print({"v": nan} == {"v": float("nan")}) # False, different objectsGetting the nth item
Since the order is stable, you can pick items by position, at a linear cost.
from itertools import islice
d = {"a": 1, "b": 2, "c": 3}
first_key = next(iter(d))
second_item = next(islice(d.items(), 1, None))
print(first_key) # a
print(second_item) # ('b', 2)next(iter(d)) is the idiomatic way to get the first key. It runs in constant time. Reaching the nth entry requires walking past the earlier ones.
Summary
- Dictionaries iterate in insertion order, guaranteed since Python 3.7.
- Reassigning a key keeps its position, while deleting and re-adding moves it to the end.
==ignores order, so equal dictionaries can iterate differently.OrderedDictequality is order-sensitive between twoOrderedDictobjects.- Keys that compare equal and hash equally, such as
1,1.0andTrue, collapse into one entry.
Exercise
What does this code print? d = {"a": 1, "b": 2, "c": 3} d["a"] = 10 del d["b"] d["b"] = 20 print(list(d.items())) print(d == {"c": 3, "b": 20, "a": 10})
Show answer
The first line prints [('a', 10), ('c', 3), ('b', 20)]. Assigning to "a" keeps its position, deleting "b" removes it, and adding "b" again places it at the end. The second line prints True, because equality ignores insertion order.
Exercise
Why does {1: "x", True: "y", 1.0: "z"} have only one entry, and what are its key and value?
Show answer
The keys 1, True and 1.0 are equal and have the same hash, so Python treats them as one key. The first key object, 1, is kept, and each later assignment replaces the value. The result is {1: 'z'}.
Exercise
You have two dictionaries a and b. Write an expression that is True only when they have the same items in the same order.
Show answer
list(a.items()) == list(b.items()). The == operator on dictionaries ignores order, so you compare the item sequences instead.