Python program to merge dictionaries

Learn 5 useful ways to merge dictionaries in Python.

Python program to merge dictionaries

Prerequisite knowledge

  1. Python dictionary
  2. *args vs **kwargs in Python

Method 1 - Using ** operator

Code

x = {"name":"Pylenin", "age":30}
y = {"city":"Gurgaon", "age":29}

print({**x, **y})

Output

{'name': 'Pylenin', 'age': 29, 'city': 'Gurgaon'}

Method 2 - Using | operator

Note:- The | operator can only be used in Python 3.9 and above.

Code

x = {"name":"Pylenin", "age":30}
y = {"city":"Gurgaon", "age":29}

print(x|y)

Output

{'name': 'Pylenin', 'age': 29, 'city': 'Gurgaon'}

Method 3 - Using update()

By using update() in Python 3, one dictionary can be merged into another. Note:- This will change the original dictionary.

Code

x = {"name":"Pylenin", "age":30}
y = {"city":"Gurgaon", "age":29}

x.update(y)
print(x)

Output

{'name': 'Pylenin', 'age': 29, 'city': 'Gurgaon'}

Method 4 - Unpack the second dictionary

This method only works if the keys of the second dictionary are strings.

Python will throw a TypeError if it encounters any integer value keys.

Code

x = {"name":"Pylenin", "age":30}
y = {"city":"Gurgaon", "age":29}

z = dict(x, **y)
print(z)

Output

{'name': 'Pylenin', 'age': 29, 'city': 'Gurgaon'}

Method 5 - Using collections library

Use the ChainMap method in collections module to merge two dictionaries.

Note - If both the dictionaries contain the same keys, then the values from the first dictionary are fetched in the final output.

Code

from collections import ChainMap

x = {"name":"Pylenin", "age":30}
y = {"city":"Gurgaon", "age":29}

z = ChainMap(x, y)
print(dict(z))

Output

{'city': 'Gurgaon', 'age': 30, 'name': 'Pylenin'}

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe