- 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:
- How to Merge Dictionaries in Python
- How to Merge Dictionaries in Python Using a For Loop
- How to Merge Dictionaries in Python Using the dict.update() Method
- How to Merge Dictionaries in Python Using the ** operator
- How to Merge Dictionaries in Python Using the | Operator
- Conclusion
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 combine two dicts = [value , dict1Python combine 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 combine two dicts = [value , dict1Python combine 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:
How to Merge Dictionaries in Python
Ashutosh Krishna
In Python, a dictionary is a collection you use to store data in pairs. It is ordered and mutable, and it cannot store duplicate data.
We write a dictionary using curly brackets like this:
Sometimes, we need to merge two or more dictionaries to create a bigger dictionary. For example:
dict_one = < "id": 1, "name": "Ashutosh", "books": ["Python", "DSA"] >dict_two = < "college": "NSEC", "city": "Kolkata", "country": "India" >merged_dict =
In the merged_dict we have the key-value pairs of both dict_one and dict_two . This is what we wish to achieve programmatically.
There are various ways we can do this in Python:
- Using a for loop
- Using the dict.update() method
- Using the ** operator
- Using the | (Union) operator (for Python 3.9 and above)
Let’s explore each way one after another.
How to Merge Dictionaries in Python Using a For Loop
We can merge two or more dictionaries using for loop like this:
>>> dict_one = < . "id": 1, . "name": "Ashutosh", . >>>> dict_two = < . "books": ["Python", "DSA"], . "college": "NSEC", . >>>> dict_three = < . "city": "Kolkata", . "country": "India" . >>>> for key,value in dict_two.items(): . merged_dictPython combine two dicts = value . >>> merged_dict >>> for key,value in dict_three.items(): . merged_dictPython combine two dicts = value . >>> merged_dict
But the problem with this method is that we need to run so many loops to merge the dictionaries.
How to Merge Dictionaries in Python Using the dict.update() Method
If you explore the dict class, there are various methods inside it. One such method is the update() method which you can use to merge one dictionary into another.
>>> dict_one = < . "id": 1, . "name": "Ashutosh", . "books": ["Python", "DSA"] . >>>> dict_two = < . "college": "NSEC", . "city": "Kolkata", . "country": "India" . >>>> dict_one.update(dict_two) >>> dict_one
But the problem when we use the update() method is that it modifies one of the dictionaries. If we wish to create a third dictionary without modifying any of the other dictionaries, we cannot use this method.
Also, you can only use this method to merge two dictionaries at a time. If you wish to merge three dictionaries, you first need to merge the first two, and then merge the third one with the modified dictionary.
>>> dict_one = < . "id": 1, . "name": "Ashutosh", . >>>> dict_two = < . "books": ["Python", "DSA"], . "college": "NSEC", . >>>> dict_three = < . "city": "Kolkata", . "country": "India" . >>>> dict_one.update(dict_two) >>> dict_one >>> dict_one.update(dict_three) >>> dict_one
Let’s explore some other options.
How to Merge Dictionaries in Python Using the ** operator
You can use the double-asterisk (**) method to unpack or expand a dictionary like this:
>>> dict_one = < . "id": 1, . "name": "Ashutosh", . >>>> dict_two = < . "books": ["Python", "DSA"] . "college": "NSEC", . >>>> dict_three = < . "city": "Kolkata", . "country": "India" . >>>> merged_dict = <**dict_one, **dict_two, **dict_three>>>> merged_dict
Using the ** operator to merge the dictionaries doesn’t affect any of the dictionaries.
How to Merge Dictionaries in Python Using the | Operator
Starting with Python 3.9, we can use the Union ( | ) operator to merge two or more dictionaries.
>>> dict_one = < . "id": 1, . "name": "Ashutosh", . >>>> dict_two = < . "books": ["Python", "DSA"], . "college": "NSEC", . >>>> dict_three = < . "city": "Kolkata", . "country": "India" . >>>> merged_dict = dict_one | dict_two | dict_three >>> merged_dict
This is the most convenient method available for merging dictionaries in Python.
Conclusion
We have explored several different methods for merging dictionaries. If you have Python 3.9 or above, you should use the | operator. But if you use older versions of Python, you can still use the other methods discussed above.
Ashutosh Krishna
Application Developer at Thoughtworks India
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.