• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Dictionary / Merge Dictionaries in Python

Merge Dictionaries in Python

Author: Aditya Raj
Last Updated: April 22, 2021

While programming, there may be situations where we need to merge two or more dictionaries in python. In this article, we will study how we can merge two or more dictionaries in python using different ways.

Merge dictionaries using items() method.

We can merge two dictionaries using items() method by adding items of a dictionary to another dictionary one by one. The items() method when invoked on a dictionary, returns a list of tuples containing the key value pair. If we have to merge two dictionaries, we will take items of a dictionary one by one and add it to another dictionary as follows. 

dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
for key,value in dict2.items():
    dict1[key]=value
print("Merged dictionary is:")
print(dict1)

Output:

First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

While using the above method, we have to consider the point that if there are common keys between the two dictionaries, the final dictionary will have common keys with values from the second dictionary from which we have extracted the items. Also only the first dictionary, to which the items are being added gets modified and nothing happens to the second dictionary.

Merge dictionaries using popitem() method.

The popitem() method is used to delete an item from a python dictionary. When invoked on a dictionary the popitem() method deletes the most recently added item in the dictionary and returns the item in the form of a tuple as key value pair.

To merge the dictionaries, we will pop the items from a dictionary using the popitem() method and will keep adding it to another dictionary.

dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
while dict2:
    key,value=dict2.popitem()
    dict1[key]=value
print("Merged dictionary is:")
print(dict1)

Output:

First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 6: 36, 5: 25, 4: 16}

While using the above method, we have to keep in mind that both the dictionaries which are to be merged get modified. The second dictionary from which the items are being pooped out becomes empty while the first dictionary to which items are being added also gets modified. Again, we will have to consider the point that if there are common keys between the dictionaries which are being merged, the merged dictionary will contain values from the second dictionary from which the items were popped out for the common keys.

Using keys() method.

We can also use keys() method to merge two dictionaries in python. The keys() method when invoked on a dictionary, returns the list of keys in the dictionary. We will use the keys() method to take all the keys from a dictionary and after that we can access the associated values of the keys. After that we can add the key value pair into another dictionary as follows.  

dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
keylist=dict2.keys()
for key in keylist:
    dict1[key]=dict2[key]
print("Merged dictionary is:")
print(dict1)

Output:

First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

When we merge two dictionaries using above method in python , we have to keep in mind that second dictionary from which we are getting the keys doesn’t get modified. Only the dictionary to which keys and values are getting added gets modified. Also, if the two dictionaries being merged have keys in common then the merged dictionary will have the values for the common keys from the dictionary from which the keys were obtained.

Merge dictionaries using update() method

We can directly merge a dictionary to another dictionary using update() method. The update() method is invoked on a dictionary and it takes another dictionary as input argument. We can merge the dictionaries using the update() method as follows.

dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
dict1.update(dict2)
print("Merged dictionary is:")
print(dict1)

Output:

First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

In this case, when we merge two dictionaries using update() method in python, the common keys are assigned the values which are present in the dictionary which is passed as argument. Also the second dictionary which is passed as argument doesn’t get modified while the first dictionary on which the update() method is invoked gets modified and is turned into final dictionary.

Merge dictionaries using ** operator

Double asterisk (**) operator is used to pass variable length keyword parameters to a function. We can also use ** operator to merge two dictionaries. When we apply ** operator to a dictionary, it deserializes the dictionary and converts it to a collection of key value pairs and then a new dictionary is formed using the key value pairs.

dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
mergedDict={**dict1,**dict2}
print("Merged dictionary is:")
print(mergedDict)

Output:

First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

We can merge any number of dictionaries at once using ** operator. Also, none of the original dictionaries which have to be merged are modified. They remain as it is. In this method too, when the dictionaries to be merged have common keys, the values for the respective keys will be taken from the dictionaries which come last in the sequence while merging.

Conclusion

In this article, we have seen how to merge dictionaries in python using different methods. We can also write the programs used in this article with exception handling using python try except to make the programs more robust and handle errors in a systematic way. Stay tuned for more informative articles.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Dictionary Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us