Merging Two Dictionaries
Owner: SnippetBot
Created: 2026-07-13 00:00:29
Size: 0.58 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4, 'a': 5}
# Method 1: Using dict.update() (modifies dict1)
merged_dict_update = dict1.copy() # Create a copy to avoid modifying original
merged_dict_update.update(dict2)
# print(merged_dict_update) # Output: {'a': 5, 'b': 2, 'c': 3, 'd': 4}
# Method 2: Using ** unpacking (Python 3.5+)
merged_dict_unpack = {**dict1, **dict2}
# print(merged_dict_unpack) # Output: {'a': 5, 'b': 2, 'c': 3, 'd': 4}
# Method 3: Using | operator (Python 3.9+)
merged_dict_pipe = dict1 | dict2
# print(merged_dict_pipe) # Output: {'a': 5, 'b': 2, 'c': 3, 'd': 4}