python
40 lines · 8 steps
Five ways to merge dicts in Python
A tour of comprehension, in-place union, reduce, recursion, and ChainMap approaches to combining mappings.
Explained by
highlit
1from collections import ChainMap
2from functools import reduce
3from typing import Any, Iterable, Mapping
4
5
6def merge(*dicts: Mapping[str, Any]) -> dict[str, Any]:
7 return {k: v for d in dicts for k, v in d.items()}
8
9
10def merge_spread(*dicts: Mapping[str, Any]) -> dict[str, Any]:
11 result: dict[str, Any] = {}
12 for d in dicts:
13 result |= d
14 return result
15
16
17def merge_reduce(dicts: Iterable[Mapping[str, Any]]) -> dict[str, Any]:
18 return reduce(lambda acc, d: {**acc, **d}, dicts, {})
19
20
21def deep_merge(base: Mapping[str, Any], override: Mapping[str, Any]) -> dict[str, Any]:
22 merged = dict(base)
23 for key, value in override.items():
24 if (
25 key in merged
26 and isinstance(merged[key], Mapping)
27 and isinstance(value, Mapping)
28 ):
29 merged[key] = deep_merge(merged[key], value)
30 else:
31 merged[key] = value
32 return merged
33
34
35def first_wins_view(*dicts: Mapping[str, Any]) -> ChainMap[str, Any]:
36 return ChainMap(*dicts)
37
38
39def last_wins_view(*dicts: Mapping[str, Any]) -> ChainMap[str, Any]:
40 return ChainMap(*reversed(dicts))
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Later dicts win by default in most merges, since their keys overwrite earlier ones.
- 2Deep merging requires recursion to combine nested mappings instead of replacing them wholesale.
- 3ChainMap gives a lazy layered view without copying, and reversing the layers flips precedence.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 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
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 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/five-ways-to-merge-dicts-in-python-explained-python-9ca1/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.