Deep Merge Nested Dictionaries
Recursively merge configuration dictionaries so nested sections are combined rather than replaced wholesale by a later override.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.