Deep Merge Nested Dictionaries

Recursively merge configuration dictionaries so nested sections are combined rather than replaced wholesale by a later override.

PythonConfig Management

Code

pythonsnippet
20 lines
from copy import deepcopy
from typing import Any, Dict


def deep_merge(base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]:
    result = deepcopy(base)
    for key, value in override.items():
        current = result.get(key)
        if isinstance(current, dict) and isinstance(value, dict):
            result[key] = deep_merge(current, value)
        else:
            result[key] = deepcopy(value)
    return result


merged = deep_merge(
    {"db": {"host": "localhost", "pool": {"min": 1}}},
    {"db": {"pool": {"max": 10}}},
)
print(merged)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

{'db': {'host': 'localhost', 'pool': {'min': 1, 'max': 10}}}

What the code does

Deep Merge Nested Dictionaries is built around the function deep_merge.

Repetition is confined to for key, value in override.items() — the rest of the file is straight-line.

Applying it

Entry signature: def deep_merge(base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]

deep_merge is what another module would consume; nothing else here is load-bearing for callers.

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. Every import resolves inside the standard library — `copy`, `typing`. The file defines `deep_merge` at load time.