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
a | b(Python 3.9 and newer) makes a new dictionary with the keys ofa, then the keys ofb. The two original dictionaries do not change, as the second line of output shows.themeandfont_sizeare in both dictionaries, so the values fromuser_settingsare kept.autosaveis only indefaults, so it stays as it is.- This is a common pattern for settings: start with the defaults, then apply what the user chose.
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.