Skip to main content

How to merge two dictionaries in Python

How to merge two dictionaries in Python.

Here's a detailed step-by-step tutorial on how to merge two dictionaries in Python.

Step 1: Define two dictionaries​

First, we need to define two dictionaries that we want to merge. Let's call them dict1 and dict2. Here's an example:

dict1 = {'name': 'John', 'age': 25}
dict2 = {'city': 'New York', 'country': 'USA'}

Step 2: Use the update() method​

In Python, dictionaries have a built-in update() method that allows us to merge dictionaries. We can use this method to merge dict2 into dict1. Here's how to do it:

dict1.update(dict2)

After executing this line, dict1 will contain the merged dictionary.

Step 3: Printing the merged dictionary​

To verify that the merge was successful, we can print the merged dictionary. Here's an example:

print(dict1)

This will output the merged dictionary:

{'name': 'John', 'age': 25, 'city': 'New York', 'country': 'USA'}

Example with overlapping keys​

If the dictionaries have keys in common, the update() method will update the values for those keys in dict1 with the values from dict2. Let's see an example:

dict1 = {'name': 'John', 'age': 25, 'city': 'London'}
dict2 = {'city': 'New York', 'country': 'USA'}

dict1.update(dict2)
print(dict1)

The output will be:

{'name': 'John', 'age': 25, 'city': 'New York', 'country': 'USA'}

As you can see, the value for the city key was updated to 'New York'.

Merging multiple dictionaries​

If you have more than two dictionaries to merge, you can use the update() method multiple times. Here's an example:

dict1 = {'name': 'John', 'age': 25}
dict2 = {'city': 'New York', 'country': 'USA'}
dict3 = {'occupation': 'Engineer'}

dict1.update(dict2)
dict1.update(dict3)

print(dict1)

The output will be:

{'name': 'John', 'age': 25, 'city': 'New York', 'country': 'USA', 'occupation': 'Engineer'}

By calling update() on dict1 multiple times, we can merge all the dictionaries into a single one.

That's it! You now know how to merge two dictionaries in Python using the update() method. Happy coding!