How to merge two Python dictionaries in a single expression in Python?

Summary: To merge two dictionaries dict1 and dict2 in a single expression, use the dictionary unpacking feature z = {**dict1, **dict2}. This creates a new dictionary and unpacks all (key-value) pairs into the new dictionary. Duplicate keys are automatically resolved by this method.

Mastering dictionaries is one of the things that differentiates the expert coders from the intermediate coders. Why? Because dictionaries in Python have many excellent properties in terms of runtime—and they’re very easy to use and understand. You cannot write effective code in Python without leveraging this powerful data structure. So, let’s dive into the mission-critical question:

Problem: Given two dictionaries; how to merge the two dictionaries using a single expression?

Consider the following snippet for reference:

dict1 = {'value1': 100, 'value': 200}
dict2 = {'value': 300, 'value2': 400}
dict1.update(dict2)
print(dict1)

Output:

dict1:  {'value1': 100, 'value': 200 , 'value': 400}

Here the output is the desired solution that we want, however, the update statement modifies the contents of dict1 which is not what we want. The purpose of the code is to find a solution that will find the union of the two dictionaries without modifying the contents of the original dictionaries. Also, the resulting dictionary should have values such that common values of dict2 override contents of dict1 as shown in the above example. 

Now that we have an overview of our problem, let us dive into the probable solutions for our problem statement.

Let’s get a quick overview of the first three solutions discussed in this article:

Exercise: Run the code. Are all methods the same? Try new dictionaries.

Method 1: Using **kwargs 

In Python 3.5 and above we can make use of the keyword argument syntax (**kwargs) to achieve our output in a single expression. Using the double asterisk ** syntax we can pass all elements of the two dictionaries and store them in a third dictionary without altering the elements of the original dictionaries (dict1 and dict2 in our case).  

The code given below explains the above concept (please follow the comments for a better grip on the code):   

dict1 = {'value1': 100, 'value': 200}
dict2 = {'value': 300, 'value2': 400}
print("dict1: ", dict1)
print("dict2: ", dict2)
z = {**dict1, **dict2}  # using ** syntax to pass and store contents of dict1 and dict2 in z
print("MERGED DICTIONARY: ", z)

Output:

dict1:  {'value1': 100, 'value': 200}
dict2:  {'value': 300, 'value2': 400}
MERGED DICTIONARY:  {'value1': 100, 'value': 300, 'value2': 400}

Here we can also use z=dict(dict2, **dict1) instead of using z = {**dict1, **dict2} which will yield us the same result. Try it yourself to get hold of it!

Method 2: Defining a function to return the merged dictionary

**kwargs has been defined in the Python 3.5 documentation and has not been implemented in previous versions. However many organizations still run their code on older versions of Python, hence the workaround in such situations is to create a function and make use of the update() and copy() methods and then return the output.

Let us have a look at the code given below to understand the above concept.

(Please follow the comments for a better grip on the code):

dict1 = {'value1': 100, 'value': 200}
dict2 = {'value': 300, 'value2': 400}
print("dict1: ", dict1)
print("dict2: ", dict2)


def combine_dicts(a, b):
  merge = a.copy()  # Returning a shallow copy of the list dict1, that is copying contents of dict1 in merge
  merge.update(b)  # merging contents dictionary merge and dict2
  return merge  # returning the merged dictionary


z = combine_dicts(dict1, dict2)  # calling function using a single expression
print("MERGED DICTIONARY: ", z)

Output:

dict1:  {'value1': 100, 'value': 200}
dict2:  {'value': 300, 'value2': 400}
MERGED DICTIONARY:  {'value1': 100, 'value': 300, 'value2': 400}

Method 3: Using a Lambda function

Since a lambda function can only have a single expression, hence using a lambda function can be a very good workaround for our problem. 

Let us look at the following code that uses a lambda function to merge two arrays (Please follow the comments for a better grip on the code):

dict1 = {'value1': 100, 'value': 200}
dict2 = {'value': 300, 'value2': 400}
print("dict1: ", dict1)
print("dict2: ", dict2)
"""lambda function that accepts and copies dict1 in l,
then updates l by merging it with dict1 and
finally returning the value of l """
merge = (lambda l=dict1.copy(): (l.update(dict2), l)[1])()
print("MERGED DICTIONARY: ", merge)

Output:

dict1:  {'value1': 100, 'value': 200}
dict2:  {'value': 300, 'value2': 400}
MERGED DICTIONARY:  {'value1': 100, 'value': 300, 'value2': 400}

Method 4: Using ChainMap container

Python 3 has a ChainMap container which is used to encapsulate two or more dictionaries into a single dictionary. Thus we can use ChainMap to merge our dictionaries as shown in the following code:

from collections import ChainMap
dict1 = {'value1': 100, 'value': 200}
dict2 = {'value': 300, 'value2': 400}
merge = dict(ChainMap({}, dict2, dict1))
print("dict1: ", dict1)
print("dict2: ", dict2)
print("MERGED DICTIONARY: ", merge)

Output:

dict1:  {'value1': 100, 'value': 200}
dict2:  {'value': 300, 'value2': 400}
MERGED DICTIONARY:  {'value1': 100, 'value': 300, 'value2': 400}

Method 5: Using | operator

In the upcoming Python release which is Python 3.9 merging dictionaries in Python can be done using a simple dictionary union operator. Let us have a look at the upcoming python operator that will merge two dictionaries in the following code:

Disclaimer: The code will work only in Python3.9 or later versions

dict1 = {'value1': 100, 'value': 200}
dict2 = {'value': 300, 'value2': 400}
merge = dict1 | dict2
print("dict1: ", dict1)
print("dict2: ", dict2)
print("MERGED DICTIONARY: ", merge)

Output:

dict1:  {'value1': 100, 'value': 200}
dict2:  {'value': 300, 'value2': 400}
MERGED DICTIONARY:  {'value1': 100, 'value': 300, 'value2': 400}

Before we wrap up, here’s a little coding practice for you. Can you guess the output of the following code?

import collections

dict1 = {'value1': 100, 'value': 200}
dict2 = {'value': 300, 'value2': 400}
merge = collections.ChainMap(dict1, dict2).maps
print("MERGED DICTIONARY: ", merge)

I hope you found this article useful and it helps you to merge two dictionaries with ease! Stay tuned for more interesting stuff in the future.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!