You can merge two dictionaries in Python using several methods. Here are the most common ways:
update()
Method (Modifies Original Dictionary)update()
method adds key-value pairs from one dictionary to another.dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
dict1.update(dict2) # Modifies dict1
print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4}
* Best when you want to modify an existing dictionary.
**
) (Creates a New Dictionary)dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'a': 1, 'b': 3, 'c': 4}
* Best when you want to create a new merged dictionary.
|
Operator (Python 3.9+)|
merges two dictionaries and returns a new one.dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged_dict = dict1 | dict2
print(merged_dict) # Output: {'a': 1, 'b': 3, 'c': 4}
* Best when using Python 3.9+ and you need a clean syntax.
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged_dict = {key: dict2.get(key, dict1.get(key)) for key in dict1.keys() | dict2.keys()}
print(merged_dict) # Output: {'a': 1, 'b': 3, 'c': 4}
* Best when you need custom merging logic.
Method | Modifies Original? | Creates New Dict? | Python Version |
---|---|---|---|
update() |
Yes | No | Any |
** (Unpacking) |
No | Yes | 3.5+ |
` | ` (Union Operator) | No | Yes |
Dictionary Comprehension | No | Yes | Any |