compare approaches one problem · three ways
Compare Approaches
The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.
Merging dicts: update() vs {**a, **b} vs |behaves differently
Apply user settings on top of defaults, then look at the defaults again.
what differs
All give the same merged settings, with later values winning. update() changes defaults itself (settings is just another name for it), which is why the first output shows modified defaults.
at a glance
| approach | use it when |
|---|---|
| A · a.update(b) | You mean to change the first dict in place. |
| B · {**a, **b} | A new merged dict that works on Python 3.5+. |
| C · a | b | A new merged dict, most readable form (Python 3.9+); a |= b updates in place. |
Watch out: All three are shallow: nested dicts are shared, not merged. Use a recursive merge for nested configuration.
the outputs
Each approach runs on the same input.
concepts
aliasingdict union
learn it
related comparisons