Merge multiple python dictionaries

In this python article we are going to see, How to merge two or more dictionaries? There are many different ways to merge multiple dictionaries and here we are going to cover few of them. There are certain advantages of each way of merging so let’s them one by one.

  1. Python Dictionary update method.
  2. Converting dictionaries into individual list objects and then adding them.
  3. Using python ** dictionary unpacking operator.
How to merge multiple (two) python dictionaries into a new python dictionary.

Merge dictionaries using dictionaries update() method.

# Create two dictionary.
Dictionary_1 = {'a':1, 'b':2}
Dictionary_2 = {'b':10, 'c':11}

# Merge content of one dictionary into other using python update() method.
Dictionary_1.update(Dictionary_2)
print(Dictionary_1)

#Output:
{'a': 1, 'b': 10, 'c': 11}

Here in above example we have merged content from Dictionary_2 into Dictionary_1. Due to this content of Dictionary_1 got modified permanently which is not our requirement. We want to create a new directory with contents from both the directories merged.

# Create two dictionary.
Dictionary_1 = {'a':1, 'b':2}
Dictionary_2 = {'b':10, 'c':11}

# Merge two dictionaries using python update() method.
New_Dictionary = Dictionary_1.copy()
New_Dictionary.update(Dictionary_2)
print(New_Dictionary)

#Output:
{'a': 1, 'b': 10, 'c': 11}

You must have noticed in above examples that in both the dictionaries element “b” is common and we have merged the value of “b” from Dictionary_2 in new dictionary.

Convert the dictionaries into list objects and then merge them.

Since add operation is not supported with dictionaries object however it is possible to add two or multiple list objects. So in this method firstly we are going to convert our dictionaries into list objects, then add them to create a new list and again convert the new list back into a dictionary object.

# Create two dictionary.
x = {'a':1, 'b':2}
y = {'b':10, 'c':11}

# Convert two dictionaries into list objects then perform add operation then convert the new list back into a dictionary.
new_dict = dict(list(x.items()) + list(y.items()))
print(new_dict)

#Output:
{'a': 1, 'b': 10, 'c': 11}

This is very crude method of merging two dictionaries and wastage of resources.

Using python ** dictionary unpacking operator

If you are using python 3.5 or greater version of python then merging of two dictionaries is possible using dictionary unpacking operators.

# Create two dictionary.
x = {'a':1, 'b':2}
y = {'b':10, 'c':11}

# Merging two dictionaries using python dictionary unpacking operator.
new_dict = {**x, **y}
print(new_dict)

#Output:
{'a': 1, 'b': 10, 'c': 11}

So that was all about how we can merge multiple dictionaries content into a new dictionary.

Continue reading:

  1. Dictionary data type in python
  2. List data type in python
  3. List comprehension in python.


Leave a Comment