Home / Python / Example programs / Dictionaries and sets

Python program: Merge two dictionaries

Combine two dictionaries; when a key is in both, the second wins.

The code

defaults = {"theme": "light", "size": 12, "lang": "en"}
user = {"theme": "dark", "size": 14}

print(defaults | user)          # Python 3.9+
print({**defaults, **user})     # older style, same result

merged = defaults.copy()
merged.update(user)
print(merged)

Output

{'theme': 'dark', 'size': 14, 'lang': 'en'}
{'theme': 'dark', 'size': 14, 'lang': 'en'}
{'theme': 'dark', 'size': 14, 'lang': 'en'}

How it works

All three give a new combined dictionary. Later values overwrite earlier ones, which is exactly what you want for "settings with defaults".

Python features used

Learn the ideas behind it in the free lesson Dictionaries & Sets.