Programming

5 Ways to Merge Dictionaries in Python

Different ways to merge Python dictionaries along with the new operators in Python 3.9

Jimit Dholakia
Towards Data Science
3 min readJul 27, 2020

--

Image by Clker-Free-Vector-Images from Pixabay

In Python, a dictionary is a data structure that contains elements in the form of a key-value pair where keys are used to access the values of the dictionary. Python dictionaries are unordered and mutable i.e. the elements of the dictionaries can be changed.

In this article, we will explore five different ways to merge two or more dictionaries, along with a crude way.

For this article, let us create two dictionaries d1 and d2 which we want to concatenate into a single dictionary:

d1 = {'India': 'Delhi',
'Canada': 'Ottawa',
'United States': 'Washington D. C.'}

d2 = {'France': 'Paris',
'Malaysia': 'Kuala Lumpur'}

The Crude Way

You can merge two dictionaries by iterating over the key-value pairs of the second dictionary with the first one.

d3 = d1.copy()
for key, value in d2.items():
d3[key] = value

print(d3)
Output:

{'India': 'Delhi',
'Canada': 'Ottawa',
'United States': 'Washington D. C.',
'France': 'Paris',
'Malaysia': 'Kuala Lumpur'}

Now, let us see cleaner and better ways of merging the dictionaries:

Method 1: Using the update method

Dictionary has a method update() which merges the dictionary with the items from the other dictionary in place and overwrites existing keys.

d4 = d1.copy()
d4.update(d2)

print(d4)
Output:
{'India': 'Delhi',
'Canada': 'Ottawa',
'United States': 'Washington D. C.',
'France': 'Paris',
'Malaysia': 'Kuala Lumpur'}

The update method modifies the current dictionary. So you might want to create a copy of the dictionary before operating on the dictionary.

Method 2: Using the unpacking operator

We can merge dictionaries in one line by simply using the unpacking operator (**).

d5 = {**d1, **d2}

print(d5)
Output:
{'India': 'Delhi',
'Canada': 'Ottawa',
'United States': 'Washington D. C.',
'France': 'Paris',
'Malaysia': 'Kuala Lumpur'}

We can also merge multiple dictionaries using this method.

{**dict1, **dict2, **dict3}

Method 3: Using collections.ChainMap

This is, perhaps, the least known method to merge dictionaries.
ChainMap class from the Collections module groups multiple dictionaries in a single view.

from collections import ChainMap
d6 = ChainMap(d1, d2)

print(d6)
Output:
ChainMap({'Canada': 'Ottawa',
'India': 'Delhi',
'United States': 'Washington D. C.'},
{'France': 'Paris',
'Malaysia': 'Kuala Lumpur'})

This method returns an object of the ChainMap class. We can, still, use this object as we would use any other dictionary. e.g. d6[’India’] will return 'Delhi’.

However, in the case of the same keys in two dictionaries, this method will return the value of the first dictionary, unlike the other methods which return the value from the second dictionary.

x = {'A': 1, 'B': 2}
y = {'B': 10, 'C': 20}

z = ChainMap(x, y)
z['B']

# outputs 2

Method 4: Unpacking the second dictionary

We can merge the dictionaries by unpacking the second dictionary.

d7 = dict(d1, **d2)

print(d7)
Output:
{'India': 'Delhi',
'Canada': 'Ottawa',
'United States': 'Washington D. C.',
'France': 'Paris',
'Malaysia': 'Kuala Lumpur'}

However, this method only works if the keys of the second dictionary are strings.

x = {1: 'A', 2: 'B'}
y = {3: 'C', 4: 'D'}

z = dict(x, **y)
Output:
TypeError: keyword arguments must be strings

Method 5: Using the merge operator

Python 3.9 has introduced the merge operator (|) in the dict class.
Using the merge operator, we can combine dictionaries in a single line of code.

d8 = d1 | d2

print(d8)
Output:
{'India': 'Delhi',
'Canada': 'Ottawa',
'United States': 'Washington D. C.',
'France': 'Paris',
'Malaysia': 'Kuala Lumpur'}

We can also merge the dictionaries in place by using the update operator (|=).

d1 |= d2

Resources

The code snippets used in this article can be found on my GitHub page.

Let’s Connect

LinkedIn: https://www.linkedin.com/in/jimit105/
GitHub: https://github.com/jimit105
Twitter: https://twitter.com/jimit105

--

--