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 Depends, FastAPI, HTTPException from sqlalchemy import create_engine from sqlalchemy.orm import Session, sessionmaker
Wiring SQLAlchemy sessions into FastAPI
dependency-injection
orm
sessions
Intermediate
7 steps
python
import re _UNIT_SECONDS = { "w": 604800,
Parsing duration strings like 1h30m in Python
regex
parsing
validation
Intermediate
8 steps
python
import csv from collections import defaultdict from dataclasses import dataclass, field from decimal import Decimal, InvalidOperation
Aggregating CSV sales by category in Python
dataclasses
csv-parsing
defaultdict
Intermediate
8 steps
ruby
class ConfigFlattener def initialize(config) @config = config end
Flattening nested config into dotted keys
recursion
hashes
tree-traversal
Intermediate
8 steps
python
from flask import Blueprint, jsonify, request, abort from .models import Article, db from .schemas import article_schema, articles_schema
Building a REST articles API with Flask Blueprints
rest-api
blueprints
serialization
Intermediate
7 steps
ruby
def build_tree(rows, root_id: nil) children_by_parent = Hash.new { |hash, key| hash[key] = [] } rows.each do |row|
Building a tree from flat rows in Ruby
recursion
hash-grouping
tree-structure
Intermediate
5 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.