Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to merge two Dictionaries
In this tutorial, we are going to learn how to combine two dictionaries in Python. Let's see different ways to merge two dictionaries.
Using update() Method
The update() method is an inbuilt dictionary method that merges one dictionary into another. It returns None and modifies the original dictionary in place ?
# initializing the dictionaries
fruits = {"apple": 2, "orange": 3, "tangerine": 5}
dry_fruits = {"cashew": 3, "almond": 4, "pistachio": 6}
# updating the fruits dictionary
fruits.update(dry_fruits)
# printing the fruits dictionary
# it contains both the key: value pairs
print(fruits)
{'apple': 2, 'orange': 3, 'tangerine': 5, 'cashew': 3, 'almond': 4, 'pistachio': 6}
Using ** Operator (Dictionary Unpacking)
The ** operator unpacks dictionaries and allows you to merge them into a new dictionary without modifying the original ones ?
# initializing the dictionaries
fruits = {"apple": 2, "orange": 3, "tangerine": 5}
dry_fruits = {"cashew": 3, "almond": 4, "pistachio": 6}
# combining two dictionaries
new_dictionary = {**dry_fruits, **fruits}
print(new_dictionary)
{'cashew': 3, 'almond': 4, 'pistachio': 6, 'apple': 2, 'orange': 3, 'tangerine': 5}
Using | Operator (Python 3.9+)
Python 3.9 introduced the | operator for dictionary merging, providing a clean and readable syntax ?
# initializing the dictionaries
fruits = {"apple": 2, "orange": 3, "tangerine": 5}
dry_fruits = {"cashew": 3, "almond": 4, "pistachio": 6}
# merging using | operator
merged_dict = fruits | dry_fruits
print(merged_dict)
{'apple': 2, 'orange': 3, 'tangerine': 5, 'cashew': 3, 'almond': 4, 'pistachio': 6}
Comparison
| Method | Modifies Original? | Python Version | Best For |
|---|---|---|---|
update() |
Yes | All versions | In-place modification |
** operator |
No | 3.5+ | Creating new dictionary |
| operator |
No | 3.9+ | Clean, readable syntax |
Conclusion
Use update() to modify dictionaries in place, ** operator for compatibility, or | operator for modern Python versions. The choice depends on whether you need to preserve the original dictionaries and your Python version.
