How to merge two dictionaries in Python

Answered
Jan 05, 2026 533 views 1 answers
7

What is the cleanest way to combine two dictionaries?

W
Platinum 285 rep

1 Answer

30
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)
P
Answered by python_dev 1 week, 2 days ago
Platinum 447 rep

Your Answer

You need to be logged in to answer questions.

Log In to Answer

Related Questions

Hot Questions

No hot questions available.