runtime

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

approachuse 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 | bA 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

Walk the pairs

related comparisons

Assignment vs shallow copy vs deepcopy

A · a.update(b)
B · {**a, **b}
C · a | b
Compare Python Approaches · Runtime