Skip to content

Merge Python Dictionaries: update(), Unpacking and the | Operator

Python dictionaries map hashable keys to values. To merge dictionaries, choose between mutating an existing dictionary with update() and creating a new one using unpacking or the union operator.

There are two ways to merge two or more dictionaries in Python:

  • Merging dictionaries using dict.update().
  • Merging using **kwargs.

Merge two or more dictionaries using dict.update()

Python Dictionary update() is a built-in function that accepts another dictionary or an iterable object (collection of key-value pairs) as an argument. The update() method doesn’t create a new dictionary; it changes the content of the existing dictionary. Following code shows merging of two dictionary using example.

# Create dictionaries
x = {'a': 11, 'b': 21}
y = {'b': 32,  'c':4}

# Merge contents of x in y
x.update(y)

print('Updated dictionary is :')
print(x)

#Output
Updated dictionary is :
{'a': 11, 'b': 32, 'c': 4}

In case of duplicate key, update method overwrites old values of the dictionary with the new values of the updating dictionary. So as shown in the above example, that value of key ‘b’ is overwritten to 32 from 11.

Merge two or more Dictionaries using **kwargs

The ** operator is used to return the data elements stored in an iterator one by one. We can use this operator to form one dictionary object using two dictionaries. It doesn’t work with version 3.4 or lower.

Applying ** to the dictionary, de-serializes the contents of the dictionary to a collection of key-value pairs.

#Creating dictionaries
x = {'a': 11, 'b': 21}
y = {'b': 32, 'c': 4}

z = {**x, **y}
print("Merged Dictionary: ")
print(z)

#Output
Merged Dictionary: 
{'a': 11, 'b': 32, 'c': 4}

The **x and **y expanded the contents of both the dictionaries to a collection of key-value pairs. Then {} puts it into a new dictionary.

Updated practical guidance

For Python 3.9+, merged = left | right creates a new dictionary, while left |= right updates left in place. For Python 3.5+, merged = {**left, **right} creates a new dictionary. For all these approaches, when keys overlap, the right-hand value wins. Example: {‘a’: 1, ‘b’: 2} | {‘b’: 9} produces {‘a’: 1, ‘b’: 9}.

Accuracy notes and troubleshooting

The ** operator unpacks a mapping inside a dictionary display; it does not serialize or iterate values alone. update() returns None, not the merged dictionary. Merge operations are shallow: nested dictionaries are replaced, not recursively combined. Insertion order is preserved in modern Python, although dictionaries should not be described simply as unordered.

Frequently asked questions

Is this method suitable for every version? Check the platform and version notes above; older desktop versions, modern Microsoft 365, macOS and web apps can behave differently. Make a copy before bulk operations.

Leave a Reply

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