How to merge 2 dictionaries in Python (4 approaches)

Updated: February 13, 2024 By: Guest Contributor Post a comment

Overview

Welcome to this exploration of merging dictionaries in Python! Learning to combine dictionaries efficiently can significantly enhance your data manipulation capabilities in Python programming.

Understanding Dictionaries in Python

Dictionaries in Python are unordered collections used to store data values in key:value pairs. They are incredibly versatile and serve as an essential tool for managing and operating on datasets effectively.

Basic Example of Merging Dictionaries

Let’s start with the most straightforward approach to merge two dictionaries using the | operator, introduced in Python 3.9:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = dict1 | dict2
print(merged_dict)

Output:

{'a': 1, 'b': 3, 'c': 4}

This method is straightforward and effective for basic merging tasks but note that values from the second dictionary will overwrite values from the first if they share common keys.

Using the update() Method for In-Place Merging

Another basic way to combine dictionaries is through the use of the update() method:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1)

Output:

{'a': 1, 'b': 3, 'c': 4}

This method changes the first dictionary in-place to include items from the second. It’s suitable when you don’t need to keep the original dictionaries intact.

Merging Dictionaries with a Custom Merge Function

For more advanced cases, where you may need custom merge logic (e.g., adding values of common keys rather than overwriting), you can use the following approach:

def custom_merge(dict1, dict2):
    result = dict1.copy()
    for key, value in dict2.items():
        if key in result:
            result[key] += value
        else:
            result[key] = value
    return result

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 5}
merged_dict = custom_merge(dict1, dict2)
print(merged_dict)

Output:

{'a': 1, 'b': 5, 'c': 5}

In this example, common keys have their values added together instead of being overwritten. This custom function provides flexibility for complex merging logic beyond what the built-in methods offer.

Using Dictionary Comprehensions for Conditional Merging

Dictionary comprehensions can be employed for more complex merging requirements, such as conditional updates. Here’s an example where we only update values that are even:

dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'c': 4, 'd': 5, 'e': 6}
merged_dict = {**dict1, **{k: v for k, v in dict2.items() if v % 2 == 0}}
print(merged_dict)

Output:

{'a': 1, 'b': 2, 'c': 4, 'd': 5, 'e': 6}

This method combines the power of dictionary unpacking with the use of a comprehension for conditional logic, showcasing the flexibility Python provides for merging dictionaries.

Conclusion

Merging dictionaries in Python can be as simple or as complex as your project demands. Whether you’re looking for a straightforward merge with the | operator or require more intricate logic with custom functions or comprehensions, Python’s versatility makes it easily achievable. With these examples, you should feel comfortable tackling a wide range of data merging tasks in your Python projects.