9. Merge
There are three ways to combine dictionaries.
update() changes the dictionary in place:
other— a dictionary whose pairs are copied into the dictionary.- Existing keys are overwritten by the values in
other; new keys are added. - It returns
None.
| returns a new dictionary and leaves both originals unchanged:
When both dictionaries have the same key, the value from the right side wins.
|= is the in-place version of |: it updates the left dictionary like update():
Dictionary | and |= require Python 3.9 or newer; the course runtime supports them.
Coming from JavaScript? a | b returns a new dict, like {...a, ...b}. a.update(b) mutates a, like Object.assign(a, b). The right side wins on duplicate keys.
Merge with update
Create a = {"name": "Ada"} and b = {"age": 36}. Merge b into a with a.update(b), then print a.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
update overwrites existing keys
Create a = {"name": "Ada", "age": 36} and b = {"age": 37}. Merge b into a with a.update(b), then print a. The value from b replaces the existing "age".
Print exactly:
Create a free account to save your progress and unlock chapter 2.
update returns None
update() changes the dictionary in place and returns None. Create a = {"x": 1} and b = {"y": 2}. Store the result of a.update(b) in a variable named result and print result.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Merge with the pipe operator
The | operator returns a new dictionary. Create a = {"x": 1} and b = {"y": 2}, store a | b in merged, then print merged.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
The right side wins
When both dictionaries have the same key, | keeps the value from the right side.
Create a = {"x": 1} and b = {"x": 2}. Print a | b.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Merge in place with |=
|= updates the left dictionary in place, like update(). Create a = {"x": 1} and b = {"y": 2}, apply a |= b, then print a.
Print exactly:
Create a free account to save your progress and unlock chapter 2.