Manipulating dictionaries is a common task in Python programming, and at times, you may need to merge two dictionaries to consolidate data or update existing values. In this article, we’ll unravel various techniques for merging dictionaries in Python, providing practical examples to empower you with the skills needed to handle this essential operation. Whether using built-in methods like update()
, embracing dictionary unpacking, leveraging the |
operator, or crafting custom merging functions, mastering these techniques empowers you to efficiently manage and consolidate data within your Python programs.
The Basics: Using the update()
Method
The simplest way to merge two dictionaries is by using the update()
method. This method modifies the caller dictionary in place by adding key-value pairs from another dictionary.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1)
# Output: {'a': 1, 'b': 3, 'c': 4}
Dictionary Unpacking (Python 3.5 and above)
A concise and elegant approach introduced in Python 3.5 is dictionary unpacking using the {**d1, **d2}
syntax.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)
# Output: {'a': 1, 'b': 3, 'c': 4}
Using the |
Operator (Python 3.9 and above)
Starting from Python 3.9, the |
operator can be used for dictionary merging.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = dict1 | dict2
print(merged_dict)
# Output: {'a': 1, 'b': 3, 'c': 4}
Custom Function for Merging
For more control over the merging process, you can create a custom function that handles the merging logic according to your requirements.
def merge_dicts(dict1, dict2):
merged = dict1.copy()
for key, value in dict2.items():
if key in merged and isinstance(merged[key], dict) and isinstance(value, dict):
merged[key] = merge_dicts(merged[key], value)
else:
merged[key] = value
return merged
dict1 = {'a': 1, 'b': {'x': 2, 'y': 3}}
dict2 = {'b': {'y': 4, 'z': 5}, 'c': 6}
result = merge_dicts(dict1, dict2)
print(result)
# Output: {'a': 1, 'b': {'x': 2, 'y': 4, 'z': 5}, 'c': 6}