How to Merge two Dictionaries into a new Dictionary in Python

Created
Modified

Using Additional Unpacking Generalizations

Starting with Python 3.5, we can merge in with literal notation as well. See the following example:

#!/usr/bin/python3
# -*- coding: utf8 -*-

x = {"a": 1, "b": 2}
y = {"a": 3, "c": 4}

# dictionary unpacking operators 
z = {**x, **y}
print(z)
{'a': 3, 'b': 2, 'c': 4}

In dictionaries, later values will always override earlier ones.

Using | Operator

In Python 3.9.0 or greater, dict union will return a new dict consisting of the left operand merged with the right operand, each of which must be a dict. If a key appears in both operands, the last-seen value wins. For example,

#!/usr/bin/python3
# -*- coding: utf8 -*-

x = {"a": 1, "b": 2}
y = {"a": 3, "c": 4}

# Add Union Operators To dict
z = x | y
print(z)

# The augmented assignment version operates in-place:
x |= y
print(x)
{'a': 3, 'b': 2, 'c': 4}
{'a': 3, 'b': 2, 'c': 4}

Using ChainMap Method

Uou can use collections.ChainMap which groups multiple dicts or other mappings together to create a single, try this:

#!/usr/bin/python3
# -*- coding: utf8 -*-

# Import module
import collections

x = {"a": 1, "b": 2}
y = {"a": 3, "c": 4}

z = dict(collections.ChainMap(x, y))
print(z)
{'a': 1, 'c': 4, 'b': 2}

Related Tags