How to merge two dictionaries in Python
Answered
7
What is the cleanest way to combine two dictionaries?
W
Asked by
web_developer
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
Platinum
•
447 rep
Your Answer
You need to be logged in to answer questions.
Log In to Answer