- How to Merge two or more Dictionaries in Python ?
- Merge two dictionaries using dict.update()
- Frequently Asked:
- Merge two or more Dictionaries using **kwargs
- **kwargs
- Merge three dictionaries
- Merge two dictionaries and add values of common keys
- Python Dictionary Tutorial — Series:
- Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.
- Related posts:
- Python Merge Dictionaries – Merging Two Dicts in Python
- How to Merge Two Dictionaries in Python
- How to Merge Two Dictionaries in Python Using the update() Method
- How to Merge Two Dictionaries in Python Using the Double Asterisk Operator ( ** )
- How to Merge Two Dictionaries in Python Using the chain() Method
- How to Merge Two Dictionaries in Python Using the ChainMap() Method
- How to Merge Two Dictionaries in Python Using the Merge Operator ( | )
- How to Merge Two Dictionaries in Python Using the Update Operator ( |= )
- Summary
How to Merge two or more Dictionaries in Python ?
In this article we will discuss different ways to merge two or more dictionaries. Also, handle scenarios where we need to keep the values of common keys instead of overwriting them.
Merge two dictionaries using dict.update()
In Python, the Dictionary class provides a function update() i.e.
It accepts an another dictionary or an Iterable object (collection of key value pairs) as argument. Then merges the contents of this passed dictionary or Iterable in the current dictionary.
Let’s use this update() function to merge two dictionaries.
Frequently Asked:
Suppose we have two dictionaries i.e.
# Create first dictionary dict1 = < 'Ritika': 5, 'Sam': 7, 'John' : 10 ># Create second dictionary dict2 =
Both dictionaries has a common key ‘Sam’ with different values. Now let’s merge the contents of dict2 in dict1 i.e.
# Merge contents of dict2 in dict1 dict1.update(dict2) print('Updated dictionary 1 :') print(dict1)
Now the content of dict1 is,
All the elements in dict2 are added to dict1. Keys which are common in both the dictionaries will contain the values as in dict2. Basically the dictionary we are passing in update() as argument will override the common key’s values. Therefore ‘Sam’ has value 20 now.
Another important point to notice is that, we didn’t got a new dictionary. The contents of dict1 changed and now apart from its existing contents it has the contents of dict2 too. What if we want to merged the contents of 2 or dictionaries to a new dictionary ? Let’s see how to do that.
Merge two or more Dictionaries using **kwargs
**kwargs
Using **kwargs we can send variable length key-value pairs to a function. When we apply ** to a dictionary, then it expands the contents in dictionary as a collection of key value pairs.
For example, if we have a dictionary i.e.
When we apply ** to this dictionary, it de-serializes the contents of dictionary to a collection of key/value pairs i.e.
So, let’s use **kwargs to merge two or more dictionaries.
Suppose we have two dictionaries i.e.
# Create first dictionary dict1 = < 'Ritika': 5, 'Sam': 7, 'John' : 10 ># Create second dictionary dict2 =
Now merge the contents of dict1 and dict2 to a new dictionary dict3 i.e.
# Merge contents of dict2 and dict1 to dict3 dict3 = <**dict1 , **dict2>print('Dictionary 3 :') print(dict3)
Content of the new dictionary is,
How did it worked ?
**dict1 & **dict2 expanded the contents of both the dictionaries to a collection of key value pairs i.e.
Therefore, a new dictionary is created that contains the data from both the dictionaries.
Both dict1 & dict2 had one common key ‘Sam’. In dict3 value for this common key ‘Sam’ is as in dict2 because we passed the **dict2 as second argument.
Merge three dictionaries
Similarly we can merge 3 dictionaries i.e.
# Create first dictionary dict1 = < 'Ritika': 5, 'Sam': 7, 'John' : 10 ># Create second dictionary dict2 = # Create second dictionary dict3 = # Merge contents of dict3, dict2 and dict1 to dict4 dict4 = <**dict1, **dict2, **dict3>print('Dictionary 3 :') print(dict4)
Till now we have seen that while merging dictionaries, values of common keys are getting overridden. What if we want to keep all the values ?
Merge two dictionaries and add values of common keys
Suppose we have two dictionaries with common key i.e.
# Create first dictionary dict1 = < 'Ritika': 5, 'Sam': 7, 'John' : 10 ># Create second dictionary dict2 =
Now we want to merge these dictionaries in way that it should keep all the values for common keys in a list i.e.
def mergeDict(dict1, dict2): ''' Merge dictionaries and keep values of common keys in list''' dict3 = <**dict1, **dict2>for key, value in dict3.items(): if key in dict1 and key in dict2: dict3Python dict merge two dicts = [value , dict1Python dict merge two dicts] return dict3 # Merge dictionaries and add values of common keys in a list dict3 = mergeDict(dict1, dict2) print('Dictionary 3 :') print(dict3)
Both the dictionaries had a common key ‘Sam’. In the merged dictionary dict3, both the values of ‘Sam’ from dict1 & dict2 are merged to a list.
We can use this function to merge 3 dictionaries and keep the all the values for common keys i.e.
# Create first dictionary dict1 = < 'Ritika': 5, 'Sam': 7, 'John' : 10 ># Create second dictionary dict2 = # Third Dictionary dict3 = # Merge 3 dictionary and keep values of common keys in a list finalDict = mergeDict(dict3, mergeDict(dict1, dict2)) print('Final Dictionary :') print(finalDict)
Python Dictionary Tutorial — Series:
- What is a Dictionary in Python & why do we need it?
- Creating Dictionaries in Python
- Iterating over dictionaries
- Check if a key exists in dictionary
- Check if a value exists in dictionary
- Get all the keys in Dictionary
- Get all the Values in a Dictionary
- Remove a key from Dictionary
- Add key/value pairs in Dictionary
- Find keys by value in Dictionary
- Filter a dictionary by conditions
- Print dictionary line by line
- Convert a list to dictionary
- Sort a Dictionary by key
- Sort a dictionary by value in descending or ascending order
- Dictionary: Shallow vs Deep Copy
- Remove keys while Iterating
- Get all keys with maximum value
- Merge two or more dictionaries in python
Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.
Complete example is as follows :
def mergeDict(dict1, dict2): ''' Merge dictionaries and keep values of common keys in list''' dict3 = <**dict1, **dict2>for key, value in dict3.items(): if key in dict1 and key in dict2: dict3Python dict merge two dicts = [value , dict1Python dict merge two dicts] return dict3 def main(): # Create first dictionary dict1 = < 'Ritika': 5, 'Sam': 7, 'John' : 10 ># Create second dictionary dict2 = print('Dictionary 1 :') print(dict1) print('Dictionary 2 :') print(dict2) print('*** Merge two dictionaries using update() ***') # Merge contents of dict2 in dict1 dict1.update(dict2) print('Updated dictionary 1 :') print(dict1) print('*** Merge two dictionaries using ** trick ***') # Create first dictionary dict1 = < 'Ritika': 5, 'Sam': 7, 'John' : 10 ># Create second dictionary dict2 = # Merge contents of dict2 and dict1 to dict3 dict3 = <**dict1 , **dict2>print('Dictionary 3 :') print(dict3) print('*** Merge 3 dictionaries using ** trick ***') # Create second dictionary dict3 = # Merge contents of dict3, dict2 and dict1 to dict4 dict4 = <**dict1, **dict2, **dict3>print('Dictionary 4 :') print(dict4) print('*** Merge two dictionaries and add values of common keys ***') # Create second dictionary # Merge contents of dict2 and dict1 to dict3 print(dict1) print(dict2) # Merge dictionaries and add values of common keys in a list dict3 = mergeDict(dict1, dict2) print('Dictionary 3 :') print(dict3) dict3 = print(dict3) # Merge 3 dictionary and keep values of common keys in a list finalDict = mergeDict(dict3, mergeDict(dict1, dict2)) print('Final Dictionary :') print(finalDict) if __name__ == '__main__': main()
Dictionary 1 : Dictionary 2 : *** Merge two dictionaries using update() *** Updated dictionary 1 : *** Merge two dictionaries using ** trick *** Dictionary 3 : *** Merge 3 dictionaries using ** trick *** Dictionary 4 : *** Merge two dictionaries and add values of common keys *** Dictionary 3 : Final Dictionary :
Related posts:
Python Merge Dictionaries – Merging Two Dicts in Python
Ihechikara Vincent Abba
Dictionaries are one of the built-in data structures in Python. You can use them to store data in key-value pairs.
You can read about the different methods you can use to access, modify, add, and remove elements in a dictionary here.
In this article, you’ll learn how to merge two dictionaries using the following:
- The update() method.
- The double asterisk/star operator ( ** ).
- The chain() method.
- The ChainMap() method.
- The merge operator ( | ).
- The update operator ( |= ).
How to Merge Two Dictionaries in Python
In this section, we’ll discuss the different methods you can use to merge dictionaries in Python, along with code examples.
All the examples you’ll see in this article will involve the merging of two dictionaries, but you can merge as many as you want.
How to Merge Two Dictionaries in Python Using the update() Method
The update() method is a built-in method that you can use to add data to dictionaries.
Consider the dictionary below:
devBio = < "name": "Ihechikara", "age": 500, "language": "Python" >devBio.update() print(devBio) #
In the code above, we created a dictionary called devBio with three key and value pairs: .
Using the update() method, we added another key and value pair: devBio.update() .
In the same manner, we can merge two dictionaries by passing another dictionary as a parameter to the update() method. Here’s an example:
devBio = < "name": "Ihechikara", "age": 500, "language": "Python" >tools = < "dev environment": "JupyterLab", "os": "Windows", "visualization": "Matplotlib" >devBio.update(tools) print(devBio) #
In the code above, we created two dictionaries — devBio and tools .
Using the update() method, we merged the key and value pairs of the tools dictionary to the devBio dictionary: devBio.update(tools) .
The merged dictionaries looked like this:
How to Merge Two Dictionaries in Python Using the Double Asterisk Operator ( ** )
You can use the double asterisk (also called double star) operator ( ** ) to «unpack» and merge the key and value pairs of two or more dictionaries into a variable.
devBio = < "name": "Ihechikara", "age": 500, "language": "Python" >tools = < "dev environment": "JupyterLab", "os": "Windows", "visualization": "Matplotlib" >merged_bio = < **devBio, **tools>print(merged_bio) #
In the code above, we unpacked the devBio and tools dictionaries using the double asterisk operator: < **devBio, **tools>.
We then stored them in a variable called merged_bio .
How to Merge Two Dictionaries in Python Using the chain() Method
The chain() method takes multiple iterable objects as its parameter. It merges and returns the objects as one iterable object.
You have to import the chain() method from the itertools module before using it:
from itertools import chain devBio = < "name": "Ihechikara", "age": 500, "language": "Python" >tools = < "dev environment": "JupyterLab", "os": "Windows", "visualization": "Matplotlib" >merged_bio = dict(chain(devBio.items(), tools.items())) print(merged_bio) #
In the code above, we passed the dictionaries to be merged as parameters to the chain() method: chain(devBio.items(), tools.items()) .
We used the items() method to access the key and value pairs of each dictionary.
Lastly, we nested the chain() method and its parameters in the dict() method: dict(chain(devBio.items(), tools.items())) .
The dict() method can be used to create a dictionary so we used it to convert the iterable objects returned (the key and value pairs) into a dictionary, and stored them in the merged_bio variable.
How to Merge Two Dictionaries in Python Using the ChainMap() Method
The ChainMap() method works the same way as the chain() method as regards to merging dictionaries. The main difference is that you don’t need the items() method to access the key and value pairs of the dictionaries.
You can import the ChainMap() method from the collections module.
Here’s how you can use the ChainMap() method to merger two dictionaries:
from collections import ChainMap devBio = < "name": "Ihechikara", "age": 500, "language": "Python" >tools = < "dev environment": "JupyterLab", "os": "Windows", "visualization": "Matplotlib" >merged_bio = dict(ChainMap(devBio, tools)) print(merged_bio) #
You can check the explanation in the last section to understand the logic in the code above.
How to Merge Two Dictionaries in Python Using the Merge Operator ( | )
The merge operator ( | ) was first introduced in Python 3.9. It’s a shorter and simpler syntax that you can use to merge dictionaries.
from collections import ChainMap devBio = < "name": "Ihechikara", "age": 500, "language": "Python" >tools = < "dev environment": "JupyterLab", "os": "Windows", "visualization": "Matplotlib" >merged_bio = devBio | tools print(merged_bio) #
So to merge the devBio and tools dictionary, we put the | operator between them: devBio | tools .
How to Merge Two Dictionaries in Python Using the Update Operator ( |= )
The update operator ( |= ) operator is another operator that was introduced in Python 3.9.
It works just like the update() method. That is:
from collections import ChainMap devBio = < "name": "Ihechikara", "age": 500, "language": "Python" >tools = < "dev environment": "JupyterLab", "os": "Windows", "visualization": "Matplotlib" >devBio |= tools print(devBio) #
In the code above, we used the |= to mege the key and value pairs in the tools dictionary into the devBio dictionary.
Summary
In this article, we talked about dictionaries in Python. You can use them to store data in key-value pairs.
We saw how to merge two dictionaries in Python using:
- The update() method.
- The double asterisk/star operator ( ** ).
- The chain() method.
- The ChainMap() method.
- The merge operator ( | ).
- The update operator ( |= ).
Each method had its own section with code examples that showed how to use them to merge dictionaries.
Happy coding! You can learn more about Python on my blog.