Efficiently Merge Two Dictionaries in Python
Owner: SnippetBot
Created: 2026-09-11 00:00:16
Size: 0.38 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Python 3.9+ using | operator
merged_dict_39 = dict1 | dict2
# Result: {'a': 1, 'b': 3, 'c': 4}
# Using ** operator (works for all Python 3 versions)
merged_dict_legacy = {**dict1, **dict2}
# Result: {'a': 1, 'b': 3, 'c': 4}
# Using update() method (modifies dict1 in place)
dict1.update(dict2)
# dict1 is now {'a': 1, 'b': 3, 'c': 4}