Dictionaries as Tables
Merge Two Dicts
Combine a defaults dict and an overrides dict so that override values win on
shared keys. The replay shows merged filling with all defaults first, then
the second loop overwriting port and debug with the override values.
By hand
The Pythonic way
{**defaults, **overrides} unpacks both dicts into a single literal in one
expression. Later entries win on duplicate keys, so placing overrides
second gives it priority — the same rule as the two-loop version.
naive.py
defaults = {'host': 'localhost', 'port': 80, 'debug': False}
overrides = {'port': 443, 'debug': True}
merged = {}
for k, v in defaults.items():
merged[k] = v
for k, v in overrides.items():
merged[k] = v
print('RESULT:', {k: merged[k] for k in sorted(merged)})
library.py
defaults = {'host': 'localhost', 'port': 80, 'debug': False}
overrides = {'port': 443, 'debug': True}
merged = {**defaults, **overrides}
print('RESULT:', {k: merged[k] for k in sorted(merged)})
RESULT: {'debug': True, 'host': 'localhost', 'port': 443}
Implementation notes
- Python 3.9+ adds the union operator:
defaults | overridesproduces the same result as{**defaults, **overrides}and reads more clearly as a merge. - Argument order matters:
{**overrides, **defaults}would give defaults priority instead; the rightmost dict wins on any duplicate key. - Neither approach mutates the input dicts. If in-place update is acceptable,
defaults.update(overrides)modifiesdefaultsdirectly without creating a new dict.