PythonMastery

Merge two dictionaries in Python

Combine two dictionaries into one with the | operator, {**a, **b} or update(). When both have the same key, the value from the second one is kept.

Merging two dictionaries puts all their keys into one dictionary. If a key is in both, the value from the second dictionary replaces the first.

The program

python
defaults = {"theme": "light", "font_size": 14, "autosave": True}
user_settings = {"theme": "dark", "font_size": 16}

settings = defaults | user_settings
print(settings)
print(defaults)
output
{'theme': 'dark', 'font_size': 16, 'autosave': True}
{'theme': 'light', 'font_size': 14, 'autosave': True}

How it works

Other ways

python
defaults = {"theme": "light", "font_size": 14, "autosave": True}
user_settings = {"theme": "dark", "font_size": 16}

# 1. Unpacking: works in Python 3.5 and newer, also gives a new dict
print({**defaults, **user_settings})

# 2. update(): changes the first dictionary in place
merged = dict(defaults)  # copy first, so defaults stays unchanged
merged.update(user_settings)
print(merged)

# 3. |= is the in-place form of |
merged2 = dict(defaults)
merged2 |= {"autosave": False}
print(merged2)
output
{'theme': 'dark', 'font_size': 16, 'autosave': True}
{'theme': 'dark', 'font_size': 16, 'autosave': True}
{'theme': 'light', 'font_size': 14, 'autosave': False}

All of these do a shallow merge: if a value is itself a dictionary, it is replaced as a whole, not merged key by key.

Learn the idea: Dictionaries

A longer explanation: How do I merge two dictionaries in Python?