How to merge two dictionaries in Python

In this article, we’re going to explore a cool trick in Python called “merging dictionaries.” Don’t worry if that sounds a bit fancy – it’s actually all about putting two sets of information together in a smart way. Imagine you have two special boxes (we call them dictionaries) filled with key-value pairs. Each key is like a label, and each value is like a piece of data. We’ll learn how to combine these boxes to make one big box that holds all the info. This article discusses different methods by which you can merge two dictionaries. Before diving into the details, lets first have a brief introduction about dictionaries.

Getting started with dictionaries

Dictionaries serve as dynamic containers capable of holding various items, such as word definitions, name-age pairs, and more. Think of them as labeled compartments where each thing you put inside has a special name called a key. Each key has a corresponding value. So, when you want to find something, you just say the key, and the dictionary gives you back what you put inside. The cool part is that you can change and update what’s inside the box whenever you want.

With dictionaries, you can connect pieces of information. Imagine having a list of friends’ names and their favorite colors. Dictionaries help you match each name with their color, making it easy to find later. Creating dictionaries is as simple. All you need to do is to convert your data into a key, value pairs which are then enclosed in curly braces {}. Lets create a dictionary named ‘info’ which holds detail of a person with the ID 2217.

info = {"ID": "2217", "Age": 26, "Country": "UK"}

In this dictionary, there are three keys i.e., ID, age and country. The key “ID” maps to the value “2217”. The key “age” is linked to the value 26. Lastly, the key “Country” is associated with the value “UK”.

Methods to merge two Dictionaries

Merging dictionaries is like combining two cuisines and cultures into one extensive collection. This way, you have everything in one place. Similarly, in Python, dictionaries are like unique cuisines and cultures, and each dictionary contains various information. Therefore, a program that merges dictionaries can gather information from diverse sources into one collection. Through the process of merging dictionaries, you can streamline your program’s configurations and options, guaranteeing accurate and effective functionality for your application. It helps you better organize configuration data, making your app’s settings more adaptable and flexible. It’s like putting all the important info in one easy-to-reach place, making things simpler to handle.

Python offers several ways to combine two dictionaries. The update() method and the ** operator are the most popular methods for merging dictionaries in Python. But that’s not all – we’re going to dive into even more techniques to get this task done. Dictionaries in Python are super handy for quickly finding values using keys or labels and are commonly used for organizing and manipulating data.

1) An iterative approach to merge two dictionaries using loops

The most straightforward approach is to merge two dictionaries using loops. By iterating through each key-value pair in the source dictionaries and updating the target dictionary, we can easily put together information from various sources into one place.

Imagine you’re building a personalized digital recipe book that combines recipes from different cuisines. Each cuisine dictionary provides details about dishes, including ingredients and cooking instructions. To create a comprehensive recipe collection, you want to merge the data from multiple cuisine dictionaries while retaining all the unique recipes.

Consider two cuisine dictionaries:

pakistani_cuisine = {'biryani': ['rice', 'spices', 'chicken'], 'dal': ['lentils', 'spices']}
italian_cuisine = {'pasta': ['flour', 'eggs', 'tomato sauce'], 'pizza': ['dough', 'cheese', 'toppings']}

Now, let’s define a function named ‘merge_recipes’ that takes these dictionaries as arguments and utilizes for…in loops to iterate through the key-value pairs of each cuisine dictionary. During each iteration, the function updates the corresponding key-value pairs in a master ‘recipes’ dictionary, effectively merging the content of all cuisine dictionaries.

def merge_recipes(pakistani, italian):
   
   # Create dictionary to store merged recipes
    recipes = {}  
    
    # Merge Indian cuisine recipes
    for dish, ingredients in pakistani.items():
        recipes[dish] = ingredients
    
    # Merge Italian cuisine recipes
    for dish, ingredients in italian.items():
        recipes[dish] = ingredients
    
    return recipes

Finally, we invoke the ‘merge_recipes’ function with the two cuisine dictionaries as arguments and store the merged result in a ‘all_recipes’ dictionary. And then print the content of ‘all_recipes’ dictionary.

all_recipes = merge_recipes(pakistani_cuisine, italian_cuisine)
print(all_recipes)

Output:

{'biryani': ['rice', 'spices', 'chicken'], 'dal': ['lentils', 'spices'], 'pasta': ['flour', 'eggs', 'tomato sauce'], 'pizza': ['dough', 'cheese', 'toppings']}

The merged recipe collection is now stored in the ‘all_recipes’ dictionary, ready to provide a diverse range of dishes from various cuisines.

The iterative approach allows us to seamlessly integrate diverse data sources into a single comprehensive collection. But it can be less efficient when dealing with large dictionaries. Iterating through each key-value pair in multiple dictionaries and updating the main dictionary one by one might consume more time and resources especially when dealing with a substantial amount of data.

2) Using Dictionary comprehension to merge two dictionaries

Merging data from two dictionaries into a single dictionary can be elegantly achieved using dictionary comprehension. This method offers a concise and efficient approach to combine dictionary contents.

Let’s consider an example where we have two dictionaries representing information about countries and their populations, and we want to merge them using dictionary comprehension:

# Two dictionaries to merge
data = {
    'USA': 331002651,
    'China': 1439323776,
    'India': 1380004385,
    'Brazil': 212559417,
    'Pakistan': 220892340
}

new_data = {
    'Russia': 145934462,
    'Japan': 126476461,
    'Germany': 83783942
}

# Merging dictionaries using dictionary comprehension
country_population = {country: population for d in (data,new_data) for country, population in d.items()}

# Display the merged dictionary
print(country_population)

Output:

{'USA': 331002651, 'China': 1439323776, 'India': 1380004385, 'Brazil': 212559417, 'Pakistan': 220892340, 'Russia': 145934462, 'Japan': 126476461, 'Germany': 83783942}

In this example, we have two dictionaries data and new_data that store the populations of various countries. Using dictionary comprehension, we merged the key-value pairs from both dictionaries into a new dictionary called country_population. The resulting dictionary contains the combined data from both sources.

3) Merging Multiple Dictionaries into One with Unpacking Operator

When you have different data in various dictionaries, you can combine them easily into a single, comprehensive dictionary using Python’s unpacking operator (**). In Python, the ** operator is used to unpack the contents of a dictionary and pass them as keyword arguments to a function or merge dictionaries together. The resulting merged dictionary contains all the combined information, making it a convenient way to consolidate diverse data sources.

In the given example, we have three dictionaries named data1, data2, and data3, each containing distinct pieces of information. The goal is to combine these dictionaries into a single comprehensive dictionary called merged_data. To achieve this, we define a function named ‘concat’ that takes the three dictionaries as arguments. Inside the function, the unpacking operator (**data1, **data2, **data3) is employed to merge all the key-value pairs from these dictionaries into a new dictionary. Here’s the code:


# Define dictionaries containing different pieces of information
data1 = {'weekdays': ["Sunday", "Monday", "Tuesday", "Thursday", "Friday", "Saturday"]}
data2 = {'month': ['Jan', 'Feb', 'Mar', 'Apr']}
data3 = {'year': '2023'}

# Create a function to merge dictionaries
def concat(data1, data2, data3):
    merged = {**data1, **data2, **data3}
    return merged

# Invoke the function and store the merged data in 'merged_data'
merged_data = concat(data1, data2, data3)

# Print the merged dictionary
print(merged_data)

Output:

{'weekdays': ['Sunday', 'Monday', 'Tuesday', 'Thursday', 'Friday', 'Saturday'], 'month': ['Jan', 'Feb', 'Mar', 'Apr'], 'year': '2023'}

This approach avoids the need for lengthy iterations or loops. The ** operator is used to unpack the key-value pairs from the three dictionaries (data1, data2, data3) and merge them into a new dictionary called merged_data. We can see from the output that the information from all three dictionaries has been successfully merged into a merged_data.

If there are duplicate keys in the dictionaries being merged, the value of the key from the last dictionary will overwrite any previous values associated with that key. This scenario is elaborated in the upcoming section where we delve into dictionaries containing shared keys.

4) Merging Dictionaries with Shared Keys

Merging dictionaries with coexisting keys involves combining two or more dictionaries while intelligently handling duplicate keys. This approach is especially beneficial when dealing with complex datasets from different sources. Let’s explore the two cases of coexisting keys:

Case 1: Retaining Most Recent Values

Sometimes, you might want to update the merged dictionary with the most recent values for duplicate keys. This ensures that you have the latest information available. As discussed in the previous method, the unpacking operator (**) efficiently merges the data from each dictionary without altering their original structures. In this case, we will use the unpacking operator to merge two dictionaries. Here’s an example where two dictionaries have the same keys, and we want to prioritize the values from the second dictionary for keys that are common between the two dictionaries:

# Original dictionary
old_prices = {'APPLE': 150, 'GOOGLE': 2500, 'AMAZON': 3300}

# Updated dictionary with recent prices
recent_prices = {'APPLE': 160, 'GOOGLE': 2600, 'TESLA': 700}

# Merge dictionaries with prioritizing recent updates
merged_prices = {**old_prices, **recent_prices}

# Print the merged prices
print(merged_prices)

Output:

{'APPLE': 160, 'GOOGLE': 2600, 'AMAZON': 3300, 'TESLA': 700}

In this example, the old_prices dictionary contains stock prices for ‘APPLE’, ‘GOOGLE’, and ‘AMAZON’. The recent_prices dictionary has updated prices for ‘APPLE’ and ‘GOOGLE’, and it also includes a new stock ‘TESLA’. When merging the dictionaries, the recent_prices values take priority for the common keys (‘APPLE’ and ‘GOOGLE’), while the ‘AMAZON’ key remains unchanged. To merge the two dictionaries, we have used the ** operator. It allows you to combine the key-value pairs from two dictionaries into a new dictionary.

The merged dictionary merged_prices will have the updated values for ‘APPLE’ and ‘GOOGLE’, along with the ‘AMAZON’ key and the new ‘TESLA’ key from the recent_prices dictionary.

Case 2: Preserving Both Sets of Information

There are situations where you want to preserve data from both dictionaries, even when they share the same keys. Imagine you’re building an interactive travel app that combines travel recommendations from different sources. Each source provides details about travel destinations, including ratings, reviews, and descriptions. To create a comprehensive database, you want to merge the data from multiple dictionaries while retaining all the valuable information.

In this example, we have two dictionaries, source1 and source2, representing travel recommendations from different sources, each with destination names as keys and information as nested dictionaries. Create another empty dictionary merged_recommendations is an empty dictionary that will store the merged recommendations from both sources.

The following code illustrates how merging dictionaries can bring together travel information from different sources:

# Travel recommendations from different sources
source1 = {
    'Paris': {'rating': 9.5, 'review': 'Captivating architecture and exquisite cuisine.'},
    'Tokyo': {'rating': 9.8, 'review': 'Futuristic cityscape and rich cultural experiences.'}
}

source2 = {
    'New York': {'rating': 9.2, 'review': 'The city that never sleeps, full of diversity and energy.'},
    'Tokyo': {'rating': 9.7, 'review': 'Blend of tradition and modernity, a must-visit.'}
}

# Merge travel recommendations from different sources
merged_recommendations = {}

for destination, info in source1.items():
    merged_recommendations[destination] = [info]

for destination, info in source2.items():
    if destination in merged_recommendations:
        merged_recommendations[destination].append(info)
    else:
        merged_recommendations[destination] = [info]

# Print the merged travel recommendations
for destination, info_list in merged_recommendations.items():
    print(f"Destination: {destination}")
    for idx, info in enumerate(info_list, start=1):
        print(f"Source {idx}: Rating: {info['rating']} | Review: {info['review']}")
    print("-" * 30)

Output:

Destination: Paris
Source 1: Rating: 9.5 | Review: Captivating architecture and exquisite cuisine.
------------------------------
Destination: Tokyo
Source 1: Rating: 9.8 | Review: Futuristic cityscape and rich cultural experiences.
Source 2: Rating: 9.7 | Review: Blend of tradition and modernity, a must-visit.
------------------------------
Destination: New York
Source 1: Rating: 9.2 | Review: The city that never sleeps, full of diversity and energy.
------------------------------

In the above example, the first for loop iterates through each key-value pair in source1, adding the information to merged_recommendations. Similarly, the second for loop iterates through each key-value pair in source2. If the destination is already in merged_recommendations, the information is appended to the existing list of recommendations. If not, a new list is created for that destination.

Finally, the merged travel recommendations are printed. The outer loop iterates through each destination, and the inner loop iterates through each source’s recommendations for that destination, displaying the ratings and reviews. The "-" * 30 creates a visual separator between destinations.

This script showcases how to gather recommendations for each city while maintaining details from different sources. The merged recommendations retain distinct insights, allowing you to create a comprehensive travel guide that incorporates the best of various perspectives. This approach ensures your users have a complete and informed travel experience.

5) Merge Dictionaries using the update() function

Merging dictionaries using the update() function in Python is like putting information from one dictionary into another. The update() function is a built-in dictionary method that merges the contents of one dictionary into another. It takes the key-value pairs from the source dictionary and adds or updates them in the target dictionary. If keys in the source dictionary already exist in the target dictionary, their values will be updated. This method is particularly useful when you want to merge two dictionaries based on their keys and values.

Here’s an example of using the update() function to merge two dictionaries:

# Original content of dictionaries
target_dict = {'name': 'John', 'age': 25}
source_dict = {'age': 26, 'city': 'New York'}

# Update target_dict with source_dict
target_dict.update(source_dict)

# Print the merged dictionary
print(target_dict)

Output:

{'name': 'John', 'age': 26, 'city': 'New York'}

In this example, when the update() function is called, the age key in target_dict is updated to 26 from the source_dict, and the new key city is added to the target_dict, resulting in a merged dictionary with the updated and added information.

Consider another scenario where we have two dictionaries: product_info and customer_reviews. The product_info dictionary holds details about various products, while the customer_reviews dictionary contains average ratings and the number of reviews for each product. We want to merge the customer review data into the product information dictionary. Here’s how you can do this by using the update() function.

# Product information
product_info = {
    'P1001': {'name': 'Smartphone', 'category': 'Electronics', 'price': 499.99},
    'A2001': {'name': 'Running Shoes', 'category': 'Sports', 'price': 89.99},
    'B3001': {'name': 'Bluetooth Speaker', 'category': 'Electronics', 'price': 69.99},
}

# Customer reviews
customer_reviews = {
    'P1001': {'average_rating': 4.5, 'num_reviews': 120},
    'A2001': {'average_rating': 4.2, 'num_reviews': 75},
    'B3001': {'average_rating': 4.8, 'num_reviews': 150},
}

# Merge customer review data into product information using update()
for product_id, review_data in customer_reviews.items():
    if product_id in product_info:
        product_info[product_id].update(review_data)

# Print the merged product information
print(product_info)

Output

{'P1001': {'name': 'Smartphone', 'category': 'Electronics', 'price': 499.99, 'average_rating': 4.5, 'num_reviews': 120}, 'A2001': {'name': 'Running Shoes', 'category': 'Sports', 'price': 89.99, 'average_rating': 4.2, 'num_reviews': 75}, 'B3001': {'name': 'Bluetooth Speaker', 'category': 'Electronics', 'price': 69.99, 'average_rating': 4.8, 'num_reviews': 150}}

By using the update() function within a loop, we merge the customer review data into the product information dictionary based on the shared product IDs. After executing the code, the product_info dictionary includes both product details and customer review data.

The update() function is a powerful tool especially when you want to modify an existing dictionary with new data. It offers a convenient and efficient way to merge two dictionaries, resulting in cleaner and more maintainable code.

6) Combining Dictionaries with the union Operator

Another widely employed technique for merging dictionaries is through the use of the “|” operator in Python. The union operator (|) simplifies the process of merging two dictionaries into a single dictionary, making the code cleaner and more concise. Each key-value pair from both dictionaries is included, resulting in a new dictionary containing all the data.

Here’s an example of using the union (|) operator to merge two dictionaries in python:

# Employee data from two sources
dict1 = {
    'John': {'age': 30, 'position': 'Manager', 'department': 'Sales'},
    'Alice': {'age': 25, 'position': 'Engineer', 'department': 'Engineering'},
    'Bob': {'age': 28, 'position': 'Analyst', 'department': 'Finance'}
}

dict2 = {
    'Alice': {'salary': 60000, 'performance': 'Exemplary'},
    'Bob': {'salary': 55000, 'performance': 'Satisfactory'},
    'Eve': {'salary': 62000, 'performance': 'Outstanding'}
}

# Merge employee details using the union operator
employee_details = dict1 | dict2

print(employee_details)

Output

{'John': {'age': 30, 'position': 'Manager', 'department': 'Sales'}, 'Alice': {'salary': 60000, 'performance': 'Exemplary'}, 'Bob': {'salary': 55000, 'performance': 'Satisfactory'}, 'Eve': {'salary': 62000, 'performance': 'Outstanding'}}

In this example, we have employee details stored in two dictionaries dict1 and dict2. The | operator is used to merge these dictionaries. If an employee’s details exist in both dictionaries, the details from dict2 will overwrite the corresponding details from dict1.

Please note that the union operator for dictionaries (|) was introduced in Python 3.9. So, if you’re working with an earlier version of Python, you won’t be able to use the union operator directly.

Conclusion

In conclusion, this tutorial has provided a comprehensive guide on merging dictionaries in Python along with the illustrative example codes. It not only covers the essential method of joining two dictionaries using the update() function, but also delves into the elegant approach of dictionary comprehension for creating and merging dictionaries. Moreover, the tutorial describes how to handle scenarios where dictionaries share common ‘key’ values. You can choose the most suitable merging technique that aligns with your specific requirements. Apply these methods and enhance your Python programming skills through practical experience. For any queries, contact us. Happy Coding!

Leave a Comment

Your email address will not be published. Required fields are marked *