How to Merge Python Dictionaries?

In this tutorial, you will learn to merge dictionaries in python Dictionaries. A dictionary data structure is a collection of key-value pairs in which each key is unique and maps to a value.
Dictionaries are mutable data structures and can be modified by adding, removing, or updating key-value pairs.

Creating a dictionary in Python

# create a dictionary
my_dict = {"apple": 2, "banana": 3, "orange": 1}

# print the dictionary
print(my_dict)

How to merge dictionaries in Python?

To merge dictionaries in Python we can use different techniques such as

  1. Merge by Using the update() Method.
  2. Merge by Using Double Asterisk (**) Operator.
  3. Merge by Using the dict() Constructor.

Merge Dictionaries in python using the update() Method.

dict1 = {"apple": 2, "banana": 3}
dict2 = {"orange": 1, "kiwi": 4}

# merge the two dictionaries using update()
dict1.update(dict2)

# print the merged dictionary
print(dict1)

Here in this program, we have used the update() method available in the Python dictionary that can be used to merge two dictionaries.

The update method adds the key-value pairs from the second dictionary to the first dictionary. If a key already exists in the first dictionary, its value is updated with the value from the second dictionary

Output

{'apple': 2, 'banana': 3, 'orange': 1, 'kiwi': 4}

Merge dictionaries using a double asterisk (**) operator

# create two dictionaries
dict1 = {"andrew": 2, "Rojan": 3}
dict2 = {"amar": 1, "Robotman": 4}

# merge the two dictionaries using the ** operator
merged_dict = {**dict1, **dict2}

# print the merged dictionary
print(merged_dict)

The double asterisk (**) operator in Python can be used to merge two dictionaries.

If a key already exists in both dictionaries, the value from the second dictionary overwrites the value from the first dictionary while using the double asterisk(**) operator.

Output

{'andrew': 2, 'Rojan': 3, 'amar': 1, 'Robotman': 4}

Merge dictionaries using the dict() Constructor.

# create two dictionaries
dict1 = {"apple": 2, "banana": 3}
dict2 = {"orange": 1, "kiwi": 4}

# merge the two dictionaries using the dict() constructor
merged_dict = dict(list(dict1.items()) + list(dict2.items()))

# print the merged dictionary
print(merged_dict)

here dict() constructor in used to merge two dictionaries. It takes an iterable of key-value pairs as an argument and returns a new dictionary.

Output

{'apple': 2, 'banana': 3, 'orange': 1, 'kiwi': 4}

Merging two dictionaries in Python can be accomplished in several ways, such as using the update() method, the double asterisk (**) operator, or the dict() constructor.

Leave a Comment