Sling Academy
Home/Python/How to merge 2 dictionaries in Python (4 approaches)

How to merge 2 dictionaries in Python (4 approaches)

Last updated: February 13, 2024

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.

Next Article: Python: How to compare 2 dictionaries (4 approaches)

Previous Article: Python: Using variables as dictionary keys (basic and advanced examples)

Series: Working with Dict, Set, and Tuple in Python

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types