🕯️ Magic Note
The ** operator unpacks dictionaries just like it unpacks lists with *. When you put them inside {}, Python creates a new dictionary with all the unpacked pairs. Original dictionaries remain untouched.
- Works in Python 3.5 and above
- Original dictionaries are never modified
- Can merge more than two dictionaries: {**a, **b, **c}
- Keys must be hashable (strings, numbers, tuples)
| dict1 | dict2 | Result |
|---|---|---|
| {“x”: 1} | {“y”: 2} | {“x”: 1, “y”: 2} |
| {“a”: 1, “b”: 2} | {“b”: 9, “c”: 3} | {“a”: 1, “b”: 9, “c”: 3} |
| {“name”: “Ali”} | {“age”: 30, “name”: “Sara”} | {“name”: “Sara”, “age”: 30} |
Python
# Merge user defaults with user preferences
user_defaults = {“theme”: “dark”, “notifications”: True}
user_preferences = {“theme”: “light”, “language”: “en”}
final_settings = {**user_defaults, **user_preferences}
print(final_settings)
# Output: {“theme”: “light”, “notifications”: True, “language”: “en”}
Python
# Merging three dictionaries at once
a = {“x”: 1}
b = {“y”: 2}
c = {“z”: 3}
merged = {**a, **b, **c}
print(merged)
# Output: {“x”: 1, “y”: 2, “z”: 3}
Python
# Original dictionaries remain unchanged
original = {“a”: 1, “b”: 2}
update = {“b”: 99, “c”: 3}
new_dict = {**original, **update}
print(original)
# Output: {“a”: 1, “b”: 2}
print(new_dict)
# Output: {“a”: 1, “b”: 99, “c”: 3}
- Forgetting that keys are overwritten by the rightmost dictionary, not merged or combined
- Using on Python versions older than 3.5, this syntax will raise a SyntaxError
- Confusing this with dict.update() which modifies in place and returns None
⚡ Whisper
Two whispers become one. When voices clash, the last speaker wins. No argument. No echo. Just a seamless spell of union.