Skip to content

Q&A · Answered

How to merge two dictionaries in Python

asked 9 months, 1 week ago 965 views 1 answer
7

What is the cleanest way to combine two dictionaries?

1 Answer

One accepted
30

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

# Python 3.9+ (cleanest)
merged = dict1 | dict2

# Python 3.5+
merged = {**dict1, **dict2}

# Update method (modifies original)
dict1.update(dict2)

# Using ChainMap for read-only merging
from collections import ChainMap
merged = ChainMap(dict1, dict2)

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.