Sub topic 7
Merging dictionaries
This chapter assumes you can create dictionaries, read and change entries, and know that Python 3.9 or later is installed. It also assumes you understand the difference between mutating an object and building a new one. Merging combines the entries of two or more dictionaries into one, and the details that matter are which dictionary wins when keys collide, whether the originals change, and how deep the copy goes.
The collision rule
Every merge tool in Python follows one rule: when the same key appears in more than one dictionary, the value from the later dictionary wins. The tools differ in whether they build a new dictionary or change an existing one, and in what input they accept.
| Tool | Result | Changes left operand? | Accepts | Column |
|---|---|---|---|---|
| `a \ | b` | New dict | No | Dicts only |
| `a \ | = b` | Same dict `a` | Yes | Dicts or iterables of key-value pairs |
| `{**a, **b}` | New dict | No | Any mappings | |
| `a.update(b)` | `None` | Yes | Mappings, pairs, keyword arguments | |
| `ChainMap(b, a)` | Layered view | No | Mappings |
The | operator
The | operator was added in Python 3.9. It returns a new dictionary and leaves both operands untouched.
defaults = {"theme": "light", "font": 12}
overrides = {"font": 14, "lang": "en"}
merged = defaults | overrides
print(merged) # {'theme': 'light', 'font': 14, 'lang': 'en'}
print(defaults) # {'theme': 'light', 'font': 12}The key font exists in both dictionaries, so the value 14 from overrides wins. The new key lang is added at the end.
Key order in the result follows insertion order. A key that appears in both dictionaries keeps the position of its first appearance, and only its value changes. Here font stays in second position even though its value came from overrides.
You can chain the operator. It is evaluated left to right, so the rightmost dictionary has the highest priority.
base = {"level": "info", "color": False}
env = {"level": "debug"}
cli = {"color": True}
settings = base | env | cli
print(settings) # {'level': 'debug', 'color': True}This layering pattern, where defaults are overridden by the environment and then by command-line options, is the most common reason to merge dictionaries.
In-place merging with |=
The |= operator updates the left-hand dictionary. Other names bound to the same dictionary see the change.
config = {"theme": "light", "font": 12}
alias = config
config |= {"font": 14}
print(alias) # {'theme': 'light', 'font': 14}The two operators accept different input. | requires two dictionaries. |= behaves like update(), so it also accepts an iterable of key-value pairs.
d = {"a": 1}
d |= [("b", 2), ("c", 3)]
print(d) # {'a': 1, 'b': 2, 'c': 3}
try:
d | [("d", 4)]
except TypeError as exc:
print(exc) # unsupported operand type(s) for |: 'dict' and 'list'Unpacking with **
Before Python 3.9, the usual way to merge was ** unpacking inside a dictionary literal. It still works, and it has one advantage: you can mix dictionaries with literal entries in one expression.
defaults = {"theme": "light", "font": 12}
overrides = {"font": 14}
merged = {**defaults, **overrides}
print(merged) # {'theme': 'light', 'font': 14}
patched = {**defaults, "font": 16, **overrides}
print(patched) # {'theme': 'light', 'font': 14}Entries are processed from left to right, so the same "later wins" rule applies. In patched, the literal "font": 16 is replaced by the 14 from overrides that follows it.
Merging three or more dictionaries is straightforward with either style:
a, b, c = {"x": 1}, {"y": 2}, {"x": 3}
print({**a, **b, **c}) # {'x': 3, 'y': 2}
print(a | b | c) # {'x': 3, 'y': 2}update() and its return value
update() changes a dictionary in place. It accepts another mapping, an iterable of pairs, or keyword arguments.
d = {"a": 1}
d.update({"b": 2})
d.update([("c", 3)])
d.update(d=4)
print(d) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}A common mistake is to assign the result of update(). It returns None, like most methods that mutate in place.
d = {"a": 1}
result = d.update({"b": 2})
print(result) # None
print(d) # {'a': 1, 'b': 2}To get a new dictionary with update(), copy first: merged = dict(a) and then merged.update(b). The | operator does this in one step.
An older idiom to avoid
You may see dict(a, **b) in older code. It only works when every key in b is a string, because the keys become keyword arguments.
print(dict({"a": 1}, **{"b": 2})) # {'a': 1, 'b': 2}
try:
dict({"a": 1}, **{2: "two"})
except TypeError as exc:
print(exc) # keywords must be stringsThe literal form {**a, **b} has no such restriction, so prefer it or |.
print({**{1: "one"}, **{2: "two"}}) # {1: 'one', 2: 'two'}Merges are shallow
All of the tools above copy references to the values, not the values themselves. This matters in two situations.
The first is that a nested dictionary is replaced as a whole, not combined with the one it collides with.
base = {"db": {"host": "localhost", "port": 5432}}
override = {"db": {"port": 6543}}
print(base | override) # {'db': {'port': 6543}}The host entry is gone because the whole value for "db" was replaced.
The second is that mutable values are shared between the original and the merged result.
defaults = {"tags": ["x"]}
merged = defaults | {"name": "demo"}
merged["tags"].append("y")
print(defaults["tags"]) # ['x', 'y']Both dictionaries point to the same list. If you need independent values, call copy.deepcopy() on the result, as shown in the chapter on copying.
Writing a recursive merge
When nested dictionaries should be combined key by key, write a small recursive function. The function below merges nested dictionaries and lets non-dictionary values from extra replace those in base.
def deep_merge(base, extra):
result = dict(base)
for key, value in extra.items():
if isinstance(value, dict) and isinstance(result.get(key), dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
base = {"db": {"host": "localhost", "port": 5432}, "debug": False}
override = {"db": {"port": 6543}, "debug": True}
print(deep_merge(base, override))
# {'db': {'host': 'localhost', 'port': 6543}, 'debug': True}The function does not change base or extra. It still shares any nested object that exists in only one of the inputs, so deep-copy the result if you plan to mutate it.
Combining values instead of replacing them
Sometimes a collision should combine the two values, for example by adding counts. A dictionary comprehension over the merged keys handles this.
a = {"apple": 3, "pear": 1}
b = {"pear": 4, "kiwi": 2}
totals = {k: a.get(k, 0) + b.get(k, 0) for k in {**a, **b}}
print(totals) # {'apple': 3, 'pear': 5, 'kiwi': 2}The expression {**a, **b} is used here only as an ordered collection of keys. A set union such as a.keys() | b.keys() also works, but its iteration order is not guaranteed to match insertion order.
For counting, Counter supports this directly. The + operator adds counts, and update() on a counter also adds instead of replacing.
from collections import Counter
first = Counter("aab")
second = Counter("abc")
print(first + second) # Counter({'a': 3, 'b': 2, 'c': 1})Note that Counter + Counter drops entries whose total is zero or negative.
Layering without copying: ChainMap
collections.ChainMap searches several dictionaries in order and returns the first match. It does not copy any data, so changes to the underlying dictionaries show up immediately.
from collections import ChainMap
defaults = {"theme": "light", "font": 12}
overrides = {"font": 14}
settings = ChainMap(overrides, defaults)
print(settings["font"]) # 14
print(settings["theme"]) # light
defaults["theme"] = "dark"
print(settings["theme"]) # dark
print(dict(settings)) # {'theme': 'dark', 'font': 14}The priority order is the reverse of |: the first map in a ChainMap wins. Writes and deletions affect only the first map. Use ChainMap when the layers change over time or are large. Use | when you want a single, independent snapshot.
Subclasses and result types
The | operator on a plain dict returns a plain dict. A defaultdict merged with | stays a defaultdict and keeps its default factory. The {**a, **b} form always produces a plain dict, so the default factory is lost. Choose the form that matches the type you want.
Choosing a merge tool
Common errors
- Expecting the earlier dictionary to win. In every tool here except
ChainMap, the later one wins. - Using
|on Python 3.8 or earlier. It raises aTypeError, so use{**a, **b}there. - Writing
merged = a.update(b)and gettingNone. - Using
|=on a dictionary that other code also references, then being surprised by the change. - Assuming a merge copies nested lists or dictionaries. It does not.
Exercise
What does this print, and why? a = {"x": 1, "y": 2}, b = {"y": 3, "z": 4}, print(a | b) followed by print(b | a).
Show answer
The first line prints {'x': 1, 'y': 3, 'z': 4} and the second prints {'y': 2, 'z': 4, 'x': 1}. The later operand wins on the shared key y, so swapping the operands changes the value of y. The key order also changes, because the result starts with the keys of the left operand.
Exercise
Given base = {"a": {"b": 1, "c": 2}} and extra = {"a": {"c": 3}}, what does base | extra return, and which function from this chapter would keep the key b?
Show answer
base | extra returns {'a': {'c': 3}}, because the whole value for "a" is replaced. deep_merge(base, extra) returns {'a': {'b': 1, 'c': 3}}.
Exercise
Why does dict({"a": 1}, **{2: "two"}) fail while {**{"a": 1}, **{2: "two"}} succeeds?
Show answer
In the dict() call, ** passes the keys as keyword arguments, and keyword names must be strings, so the integer key raises TypeError: keywords must be strings. In a dictionary literal, ** copies entries directly and any hashable key is allowed.