Methods to combine multiple dictionaries in Python

In this tutorial, you will learn multiple methods to combine multiple dictionaries in one dictionary in Python. As we know that in dictionaries we have “Keys” and “Values” separated by a semicolon (:).

How to combine multiple dictionaries in Python

Let us take two separate dictionaries followed bu ‘a’ & ‘b’.

 

a={'a':'Shivam', 'b': 8} 
b={'d': 6, 'c':'Ramesh'}
print(a)
print(b)

As you can see in the above input, we have generated two dictionaries (a & b) and print both dictionaries.

Output–

 
{'a': 10, 'b': 8} 
{'d': 6, 'c': 4}
  • Using update( )¬† function- If you have only two dictionaries. Then you can merge both dictionaries using update( ) function.
def Merge(a,b): 
    return(b.update(a)) 
Merge(a,b)
print(b)

Note– New dictionary will combine in a variable (b) not in the variable (a).

The new dictionary will combine in only one dictionary, not in both dictionaries.

Output–

{'d': 6, 'c': 'Ramesh', 'a': 'Shivam', 'b': 8}

In the above output, both dictionaries are updated in the ‘b’ variable.

  • Using copy and update function–Using copy and update function. You can easily store & combine both dictionaries in the third variable.
h = a.copy()
h.update(b)
print(h)

Here in the above input, the dictionary stored in the variable ‘a’ is copied in ‘h’ and updated in the ‘b’ variable. Therefore both variables will combine in the third variable ‘h’.

Output–

{'a': 'Shivam', 'b': 8, 'd': 6, 'c': 'Ramesh'}
  • Using¬† (**) method– If you have no. of dictionaries stored in multiple variables then you can use (**) method to combine all dictionaries.
a={'a':'Shivam', 'b': 8}
b={'d': 6, 'c':'Ramesh'}
c={'f':'Rahul','g':'Ganesh'}
e={**a,**b,**c}
print(e)

In the above dictionary, you will see three different dictionaries stored in multiple variables. Using the (**) method, it will combine all dictionaries in another variable. Let’s see in the output section.

Output–

 

{'a': 'Shivam', 'b': 8, 'd': 6, 'c': 'Ramesh', 'f': 'Rahul', 'g': 'Ganesh'}

Here in the output, you can see, all the dictionaries are get merged in the variable ‘e’.

Leave a Reply

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