Merging two Dictionaries | Python
The main operations on a Python dictionary are storing a value with some key and extracting the value given the key. In Python, there are many methods of merging two dictionaries . In this article you can learn different ways to merge two or more dictionaries. There is no built-in function to concatenate (merge) two dictionaries together in Python, but we can make some arrangements to do that. Some of the methods need a few lines of code to merge while one can combine the dictionaries in a single expression . So, let's now step up to see the different options to solve merge two dictionaries in a single expression in Python.
Using Double asterisks (**) Operator
PEP 448 also expanded the abilities of ** by allowing this operator to be used for dumping key/value pairs from one dictionary into a new dictionary . Leveraging dictionary comprehension and the unpacking operator, you can merge the two dictionaries in a single expression .
- Python 3.5 or greater
Using Python plus (+) Operator
If you are still working in Python 2.7 , then using the plus (+) sign to combine items from the two dictionaries produces a single expression solution.
- Python 2.7
ChainMap is a data structure provided by the Python standard library that allows you to treat multiple dictionaries as one.
- Python 3.0 and later
Using Update() method
The update() method updates the dictionary with the elements from the another dictionary object or from an iterable of key/value pairs . The update() method adds element(s) to the dictionary if the key is not in the dictionary. If the key is in the dictionary, it updates the key with the new value .
- Python 2, (or 3.4 or lower)
Using | operator
- Python 3.9 and later
In the upcoming Python version 3.9 you can now merge and update Dictionaries by simply using for merging and = and for updating.
Merge multiple dictionaries
If you want to merge more than one dictionary, the simple solution is :
Comprehensions in Python provide you with a short and concise way to construct new sequences using sequences which have been already defined. In pythonic way , you can use comprehension to merge two dictionaries .
Merge Dictionary using Lambda function
A lambda function can take any number of arguments, but can only have one expression. You can use lambda function to merge two dictionaries in Python.
Merge n number of Python Dictionaries
Python itertools module standardizes a core set of iterator building blocks. It has features like fast and memory efficient . The itertools.chain returns a chain object whose .next() method returns elements from the first iterable until it is exhausted, then the next iterable(s) , until all are exhausted. If you want to merge n number of Python Dictionaries the you can use the following: