Sub topic 7
Merging dictionaries
This chapter covers three ways to combine dictionaries: the | operator, ** unpacking, and update(). It assumes you can create dictionaries, read and assign keys, and know that dictionaries are mutable. The | and |= operators need Python 3.9 or newer.
The core rule: later values win
All merge tools follow the same rule. When two dictionaries share a key, the value from the dictionary that comes later in the expression replaces the earlier one. Keys that appear in only one dictionary are kept. The merged dictionary's order starts with the left dictionary's keys. Keys that only the right dictionary has are added after them.
Building a new dictionary with `|`
The | operator returns a new dictionary and leaves both operands unchanged. The |= operator updates the left-hand dictionary in place.
defaults = {"theme": "light", "font": 12}
overrides = {"font": 14}
merged = defaults | overrides
print(merged) # {'theme': 'light', 'font': 14}
also = {**defaults, **overrides}
print(also == merged) # True
defaults |= overrides
print(defaults) # {'theme': 'light', 'font': 14}After the first merge, defaults still holds font: 12. Only the last statement, |=, changes it.
Unpacking with `**`
Inside a dictionary literal, **name inserts every key-value pair of name at that position. This works on any Python 3.5+ version. It also lets you mix in extra keys and control precedence by position:
base = {"host": "localhost", "port": 8000}
config = {**base, "port": 9000, "debug": True}
print(config) # {'host': 'localhost', 'port': 9000, 'debug': True}Here the literal "port": 9000 comes after **base, so it wins. If you wrote it before **base, the value from base would win instead.
Changing a dictionary in place with `update()`
update() modifies the dictionary it is called on and returns None. It accepts another dictionary, an iterable of key-value pairs, or keyword arguments.
settings = {"theme": "light"}
settings.update({"font": 14})
settings.update([("lang", "en")])
settings.update(theme="dark")
print(settings) # {'theme': 'dark', 'font': 14, 'lang': 'en'}d |= other behaves like d.update(other). The difference is that |= accepts only another mapping, while update() also accepts pairs and keyword arguments.
Choosing a tool
| Tool | Creates a new dictionary? | Accepts | Minimum Python | Column |
|---|---|---|---|---|
| `a \ | b` | Yes | Dictionaries only | 3.9 |
| `{**a, **b}` | Yes | Any mapping, plus extra literal keys | 3.5 | |
| `a \ | = b` | No, changes `a` | Mappings | 3.9 |
| `a.update(b)` | No, changes `a` | Mappings, pairs, keywords | All |
Use a new-dictionary form when other code still holds a reference to the original, because in-place changes affect every holder of that reference. Use an in-place form when you are building up one dictionary in a loop and no one else needs the old state.
Common errors
- Using the return value of
update(). Writingresult = d.update(x)setsresulttoNone. Callupdate()as a statement and then used. - Expecting values to be combined. Merging replaces values and never adds them.
{"n": 1} | {"n": 2}gives{"n": 2}, not3. To combine values, useCounteror a loop. - Assuming a deep merge. Merging is shallow. If both dictionaries have a nested dictionary under the same key, the right one replaces the left one entirely. The nested keys are not merged.
- Sharing nested objects. The merged dictionary refers to the same nested lists and dictionaries as its sources. Changing one nested list changes it in both places. The copying chapter covers this.
a = {"opts": {"x": 1, "y": 2}}
b = {"opts": {"x": 9}}
print(a | b) # {'opts': {'x': 9}}The key y is gone because b["opts"] replaced a["opts"] as a whole.
Exercise
Given x = {"a": 1, "b": 2} and y = {"b": 3, "c": 4}, what does {**y, **x} produce, and what does x | y produce?
Show answer
{**y, **x} gives {'b': 2, 'c': 4, 'a': 1}. The order starts with the keys of y, and x wins on b, so b is 2. x | y gives {'a': 1, 'b': 3, 'c': 4}, because y is on the right and wins on b.
Exercise
You write config = defaults.update(user_prefs) and later get TypeError: 'NoneType' object is not subscriptable when reading config["theme"]. What went wrong, and how do you fix it?
Show answer
update() changes defaults in place and returns None, so config is None. Either call defaults.update(user_prefs) and use defaults, or write config = defaults | user_prefs to get a new dictionary.