13. Override a Config Without Changing It
Difficulty: Medium · Topic: Core Python & data structures
Pipeline configs are nested dicts. Write with_override(config, path, value): return a new config in which the dotted path (such as 'db.pool.size') is set to value.
- Missing levels on the path are created as empty dicts.
configmust stay exactly as it was, at every depth. The new config must not share any dict or list with it either: changing one later must never change the other.
Your code runs in CPython on our servers against 5 tests, including hidden ones.
Sample test
cfg = {'db': {'host': 'h', 'pool': {'size': 5}}, 'debug': False}
new = with_override(cfg, 'db.pool.size', 20)
(new, cfg)Expected: ({'db': {'host': 'h', 'pool': {'size': 20}}, 'debug': False}, {'db': {'host': 'h', 'pool': {'size': 5}}, 'debug': False})
Hints
Hint 1
config.copy() and dict(config) copy only the top level: nested dicts are shared.Hint 2
copy.deepcopy(config) copies every level.Hint 3
Walk the path withnode = node.setdefault(part, {}) for every part but the last.Learn the concepts
- Mutability, copies and default arguments · 4 min read. What assignment really does, shallow versus deep copies, and the mutable default trap.
More Python problems
- Flatten a Nested List · Easy
- Squares of the Even Numbers · Easy
- Top K Frequent Words · Easy
- Invert a Dictionary · Easy
- Merge Dicts and Sum Shared Keys · Easy
- Group Records by Key · Easy
- Count Words in Reviews · Easy
- Zip Columns into Records · Easy
- Find the Missing IDs · Easy
- Safe Min and Max · Easy
- Sort by Several Keys · Medium
- Fix the Mutable Default Argument · Medium
- Keep the Last N Events · Medium