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
import click from flask.cli import AppGroup from . import db
Custom user CLI commands in Flask
cli
click
command-group
Intermediate
7 steps
python
import heapq from datetime import datetime from pathlib import Path from typing import Iterator, NamedTuple
Merging sorted log files with heapq
generators
heapq
lazy-evaluation
Intermediate
6 steps
python
import datetime from dataclasses import dataclass
Parsing fixed-width records in Python
parsing
generators
dataclasses
Intermediate
8 steps
typescript
import { Injectable, PipeTransform, ArgumentMetadata,
A custom validation pipe in NestJS
validation
dto
recursion
Intermediate
10 steps
python
from itertools import product from dataclasses import dataclass from decimal import Decimal
Generating product variants with itertools.product
cartesian-product
dataclass
decimal
Intermediate
7 steps
python
from typing import Callable, Dict, Type class PluginRegistry:
A decorator-based plugin registry in Python
decorators
registry pattern
factory
Intermediate
9 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.