Merge Dictionaries in Python

Merge Dictionaries in Python: 6 Methods With Code

If you want to know how to merge dictionaries in python then you are at the right place. Dictionaries are one of the most useful data structures in python. This makes it a frequently used data structure in many software applications. While working with dictionaries, we often need to merge two dictionaries. There are many ways to do it which we will discuss in this article. 

But before we learn about merging dictionaries, let us refresh our concepts about python dictionaries. 

What are Dictionaries in Python? 

A dictionary in python is a data structure to store data in key-value pairs in python. It stores a collection of key-value pairs where the values can be accessed with the corresponding keys. They can be declared using the dict() method or simply defining key-value pairs inside curly-braces ({})

Dictionaries are case-sensitive and ordered and do not allow duplicate key-value pairs. The keys in dictionaries are immutable, meaning they can’t be changed once defined. 

Example: 

# dictionary example 
fruits = {1 : 'apple', 2 : 'mango', 3 : 'kiwi', 4 : 'grapes'} 
print(fruits) 

Output: 

{1: ‘apple’, 2: ‘mango’, 3: ‘kiwi’, 4: ‘grapes’} 

How to Merge Dictionaries in Python? 

There are many ways to merge dictionaries in Python. Let us see them one by one. 

1. Using update() method 

The update() method allows us to merge two dictionaries. Here one dictionary is overwritten and merged to form the resultant dictionary. The benefit of this method is that no new dictionary needs to be formed. The usage has been shown below. 

Example: 

d1 = {'Rohan' : 20, 'Aryan' : 10, 'Aman' : 50} 
d2 = {'Ankita' : 30, 'Aryan' : 40, 'Raman' : 60} 
d1.update(d2) 
print(f'Merged Dictionary : {d1}') 

Output: 

See also  Convert List to String Python With The Easy Methods in 2023

Merged Dictionary : {‘Rohan’: 20, ‘Aryan’: 40, ‘Aman’: 50, ‘Ankita’: 30, ‘Raman’: 60} 

2. Using Merge (|) operator 

The merge operator (|) merges two dictionaries and returns a new merged dictionary. It is present only in python version 3.9 and above. The syntax is as follows: 

merged_dictionary = dict1 | dict2 

Example: 

d1 = {'Rohan' : 20, 'Aryan' : 10, 'Aman' : 50} 
d2 = {'Ankita' : 30, 'Aryan' : 40, 'Raman' : 60} 
d3 = d1 | d2 
print(f'Merged Dictionary : {d3}') 

Output: 

Merged Dictionary : {‘Rohan’: 20, ‘Aryan’: 40, ‘Aman’: 50, ‘Ankita’: 30, ‘Raman’: 60} 

3. Using Unpack(**) operator 

The unpack operator is by far the easiest method to merge the dictionaries. What it does is that, when applied to a dictionary, it returns all the individual key-value pairs in that dictionary. These can be used for many applications, one of them being merging dictionaries. 

In this method, we will create a new dictionary that will contain the key-value pairs of any two dictionaries, which we will do using the unpack operator. The code example is given below: 

Example: 

d1 = {'Rohan' : 20, 'Aryan' : 10, 'Aman' : 50} 
d2 = {'Ankita' : 30, 'Aryan' : 40, 'Raman' : 60} 
d3 = {**d1, **d2} 
print(f'Merged Dictionary : {d3}') 

Output: 

Merged Dictionary : {‘Rohan’: 20, ‘Aryan’: 40, ‘Aman’: 50, ‘Ankita’: 30, ‘Raman’: 60} 

We can also merge more than two dictionaries using unpack operator. It is also one of the easiest ways to merge more than two dictionaries. 

Example: 

d1 = {'Rohan' : 20, 'Aryan' : 10, 'Aman' : 50} 
d2 = {'Ankita' : 30, 'Aryan' : 40, 'Raman' : 60} 
d3 = {'Rahul' : 25, 'Aman' : 45, 'Nishtha' : 80} 
d4 = {**d1, **d2, **d3} 
print(f'Merged Dictionary : {d4}') 

Output: 

Merged Dictionary: {‘Rohan’: 20, ‘Aryan’: 40, ‘Aman’: 45, ‘Ankita’: 30, ‘Raman’: 60, ‘Rahul’: 25, ‘Nishtha’: 80} 

4. Using chainMap() method 

The chainMap() method is an inbuilt method present in the collections module. It takes two dictionaries as parameters and returns a new dictionaries containing the keys from both the pairs. It must be noted that in case of same keys in both the dictionaries, the value corresponding to the first dictionary will be taken. 

See also  PHP vs ASP.NET: Major Differences You Should Know

Example: 

from collections import ChainMap 
d1 = {'Rohan' : 20, 'Aryan' : 10, 'Aman' : 50} 
d2 = {'Ankita' : 30, 'Aryan' : 40, 'Raman' : 60} 
d3 = ChainMap(d1, d2) 
print(d3) 
print(f'Merged Dictionary : {dict(d3)}') 

Output: 

ChainMap({‘Rohan’: 20, ‘Aryan’: 10, ‘Aman’: 50}, {‘Ankita’: 30, ‘Aryan’: 40, ‘Raman’: 60}) 

Merged Dictionary: {‘Ankita’: 30, ‘Aryan’: 10, ‘Raman’: 60, ‘Rohan’: 20, ‘Aman’: 50} 

5. Using chain() method 

The chain() method is another inbuilt method that is defined in the itertools module. It takes an iterable as a parameter and returns its elements in an object until it’s empty, then it moves on to the next iterable and repeats the cycle. 

Dictionaries are also iterables, which means we can use the chain method to get an object with the elements of the dictionaries. We can then typecast the object into a dictionary to get the final merged dictionary. 

Example: 

from itertools import chain 
d1 = {'Rohan' : 20, 'Aryan' : 10, 'Aman' : 50} 
d2 = {'Ankita' : 30, 'Aryan' : 40, 'Raman' : 60} 
d3 = chain(d1, d2) 
print(d3) 
print(f'Merged Dictionary : {dict(d3)}') 

Output: 

<itertools.chain object at 0x7fdb4c6c0670> 

Merged Dictionary : {‘Rohan’: 20, ‘Aryan’: 40, ‘Aman’: 50, ‘Ankita’: 30, ‘Raman’: 60} 

6. Using Dictionary Comprehension 

Dictionary Comprehension is also one way in which we can tackle this issue. Here, we basically iterate through the dictionary, taking each key-value pair and inserting it into the new dictionary. This way we can merge two or more dictionaries in a new dictionary. 

Example: 

d1 = {'Rohan' : 20, 'Aryan' : 10, 'Aman' : 50} 
d2 = {'Ankita' : 30, 'Aryan' : 40, 'Raman' : 60} 
d3 = {key : value for d in (d1, d2) for key, value in d.items()} 
print(f'Merged Dictionary : {d3}') 

Output: 

Merged Dictionary : {‘Rohan’: 20, ‘Aryan’: 40, ‘Aman’: 50, ‘Ankita’: 30, ‘Raman’: 60} 

See also  Ruby On Rails Vs JavaScript: Top Differences To Remember

 By Adding Values of the Second Dictionary 

In all the ways we discussed above, the values for same keys in multiple dictionaries were overridden by some other dictionary. But what if we want to conserve both the values? This method does exactly that. 

The steps of this method are simple: 

  1. Merge the two dictionaries using any of the techniques mentioned above. 
  2. Iterate over both the dictionaries and check for common keys 
  3. For each common key, replace the value with a list containing the initial value and the value from the other dictionary (this step will depend on which dictionary’s values were taken in the final merged dictionary). 

The application of this method has been shown below: 

d1 = {'Rohan' : 20, 'Aryan' : 10, 'Aman' : 50} 
d2 = {'Ankita' : 30, 'Aryan' : 40, 'Raman' : 60} 
 
def mergeDict(dict1, dict2): 
    d3 = {**d1, **d2} 
    for key, value in d3.items(): 
        if key in d1 and key in d2 : 
            d3[key] = [value, d1[key]] 
    return d3 
 
d3 = mergeDict(d1, d2) 
print(d3) 

Output: 

{‘Rohan’: 20, ‘Aryan’: [40, 10], ‘Aman’: 50, ‘Ankita’: 30, ‘Raman’: 60} 

Read More

Conclusion 

Dictionaries are a very useful and frequently used data structure in python. Therefore, situations, where we need to merge two dictionaries, might arise. An example of that can be where we have a dictionary of ingredients and measurements for two recipes, eg., garlic dip and a cheese dip and we need to make an ingredient dictionary for nachos which require both dips, so we need to merge the dictionaries for both the dips as well as the nachos. 

The task of merging dictionaries can be very challenging and tedious depending on the type of elements but it can be made easier and faster using the above-mentioned techniques. 

Leave a Comment

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