python
25 lines · 6 steps
How a recursive deep merge works in Python
Combine nested dictionaries by recursing into shared keys while copying values so the inputs stay untouched.
Explained by
highlit
1from copy import deepcopy
2from typing import Any, Mapping
3
4
5def deep_merge(base: Mapping[str, Any], override: Mapping[str, Any]) -> dict:
6 result = deepcopy(dict(base))
7
8 for key, override_value in override.items():
9 base_value = result.get(key)
10
11 if isinstance(base_value, Mapping) and isinstance(override_value, Mapping):
12 result[key] = deep_merge(base_value, override_value)
13 elif isinstance(base_value, list) and isinstance(override_value, list):
14 result[key] = base_value + deepcopy(override_value)
15 else:
16 result[key] = deepcopy(override_value)
17
18 return result
19
20
21def merge_configs(*configs: Mapping[str, Any]) -> dict:
22 merged: dict = {}
23 for config in configs:
24 merged = deep_merge(merged, config)
25 return merged
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Recursing on matching Mapping keys lets you merge arbitrarily nested structures without hand-writing each level.
- 2Deep-copying values keeps the original inputs immutable, avoiding shared-reference bugs across merges.
- 3Folding a merge over a sequence turns a two-argument combiner into a variadic one with a clear precedence order.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-recursive-deep-merge-works-in-python-explained-python-d49b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.