4 Unique Ways to Merge Dictionaries in Python

Python Tutorials

Summary: In this tutorial, we will learn different ways to merge two or more dictionaries in Python.

Method 1: Using dict.update() method

The dictionary has a built-in method dict.update() that merges the key-value pairs of the other dictionary to the current dictionary object.

>>> d1 = {'website': 'pencilprogrammer.com'}
>>> d2 = {'content': 'Python'}
>>> d1.update(d2)
>>> print(d1)
{'content': 'Python', 'website': 'pencilprogrammer.com'}

The dict.update() method updates the dictionary in-place, so if the key-value pairs from the other dictionary already exists in the current one, it will override them.

Method 2: Using (**) Unpacking Operator

Another interesting way we can combine two or more dictionaries together is by using the unpacking operator.

>>> d3 = {**d1, **d2}
>>> print(d3)
{'content': 'Python', 'website': 'pencilprogrammer.com'}

In this method, we do not update the existing dictionaries, but create a new one and fill them using the unpacking operator.

Also, if the same keys are present in d2, their values will be overridden by the corresponding values of d1.

Method 3: Using dict(d1, **d2)

The dict(d1, **d2) merges two dictionaries like the above method, but only works if d2 is entirely string-keyed.

>>> d3 = dict(d1, **d2)
>>> print(d3)
{'website': 'pencilprogrammer.com', 'name': 'Python'}

Method 4: Using (|) Merge Operator

Python 3.9 has added a new operator | (called merge) to the built-in dict class that complements the above methods of combining dictionaries.

>>> d1 = {'a': 1}
>>> d2 = {'b': 2}
>>> d3 = d1 | d2
>>> print(d3)
{'a': 1, 'b': 2}

There were the 4 different ways using which we can easily combine multiple dictionares in Python language.

Leave a Reply

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