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.

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

print("dict1: ", dict1)
print("dict2: ", dict2)

z = {**dict1, **dict2} 

print("MERGED DICTIONARY: ", z)

Exercise: Which of the duplicated entry ends up in the dictionary?

Other methods to merge dictionaries include:

  1. Dictionary unpacking with **
  2. Using a lambda function.
  3. Using a Dictionary Comprehension.
  4. Using ChainMap container.
  5. Using | operator.
  6. Convert to lists and concatenate in a single line.
  7. Using itertools.chain()
  8. Using a custom function.

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.

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 the same result. Try it yourself to get hold of it!

Method 2: 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 3: 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 4: 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 5: Using A Dictionary Comprehension

Dictionary comprehensions can be extremely useful when it comes to Python one-liners though they might become a little complex to comprehend when the expression becomes long as in this case. Nevertheless, this method definitely needs to be mentioned in the list of our proposed solution because it works perfectly in our case.

Let us have a look at the following code to understand how we can use a dictionary comprehension to merge two dictionaries in a single line:

dict1 = {'value1': 100, 'value': 200}
dict2 = {'value': 300, 'value2': 400}
result = {key:value for d in [dict1,dict2] for key,value in d.items()}
print(result)

Output:

{'value1': 100, 'value': 300, 'value2': 400}

Method 6: Convert To List And Concatenate

Another approach that actually works and helps us to merge two dictionaries in a single expression is to get a list of items from each dictionary and then concatenate them.

Let us have a look at the following program which explains the above concept. (Disclaimer: This works for Python 3 and above.)

dict1 = {'value1': 100, 'value': 200}
dict2 = {'value': 300, 'value2': 400}
result = dict(list(dict1.items()) + list(dict2.items())) 
print(result)

Output:

{'value1': 100, 'value': 300, 'value2': 400}

Method 7: Using itertools.chain

chain() is a method within the itertools module that accepts a series of iterables and then returns a single iterable. The generated output which is a single iterable cannot be used directly and has to be explicitly converted. This method allows us to avoid creating extra lists as in method 6; hence it is more effective.

Let us have a look at the following code which simplifies things for us:

from itertools import chain
dict1 = {'value1': 100, 'value': 200}
dict2 = {'value': 300, 'value2': 400}
result = dict(chain(dict1.items(),dict2.items())) 
print(result)

Output:

{'value1': 100, 'value': 300, 'value2': 400}

Method 8: 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)

Conclusion

In this article we learned the following methods of merging two dictionaries in a single expression:

  1. Dictionary unpacking with **
  2. Using Lambda Function.
  3. Using ChainMap container.
  4. Using a custom function.
  5. Using dictionary comprehension.
  6. Convert to list elements and concatenate.
  7. Using itertools.chain()
  8. Using | operator.

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

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. 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?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming 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.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!