0%

🪄 Merge Without A Sound

Merge two dictionaries into one with a single breath. The unpacking operator spreads key-value pairs like whispers joining a silent stream.
🔮 z = {**dict1, **dict2}

Merging dictionaries shouldn’t require battles or noise. The unpacking operator ** does it in one breath. It spreads the key-value pairs from each dictionary into a new one. Think of it as pouring two cups into a single vessel. If the same key appears in both, the second pour overwrites the first.

🕯️ 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.

The syntax {**dict1, **dict2} creates a new dictionary that contains all items from dict1 first, then all items from dict2. Any key conflicts are resolved by dict2 taking priority.
  • 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)
💡 For Python 3.9+, you can also use the pipe operator: dict1 | dict2. The unpacking method works in older versions and is more explicit about creating a new dictionary.
dict1dict2Result
{“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}
⚠️ If you need to update an existing dictionary instead of creating a new one, use dict1.update(dict2). That modifies dict1 directly and returns None. The unpacking method always returns a brand new dictionary.
Examples

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}

Common Mistakes
  • 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.