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

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots