
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
Python program to merge two Dictionaries
In this tutorial, we are going to learn how to combine two dictionaries in Python. Let's see some ways to merge two dictionaries.
update() method
First, we will see the inbuilt method of dictionary update() to merge. The update() method returns None object and combines two dictionaries into one. Let's see the program.
Example
## 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)
If you run the above program,
Output
{'apple': 2, 'orange': 3, 'tangerine': 5, 'cashew': 3, 'almond': 4, 'pistachio': 6}
** operator for dictionaries
** helps to unpack the dictionary in some special cases. Here, we are using it to combine two dictionaries into one.
Example
## 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)
If you run the above program,
Output
{'cashew': 3, 'almond': 4, 'pistachio': 6, 'apple': 2, 'orange': 3, 'tangerine': 5}
I prefer the second method more than the first one. You can use any of the mentioned ways to combine the dictionaries. That's up to you.
If you have to doubts regarding the tutorial, please do mention them in the comment section.
- Related Articles
- C# program to merge two Dictionaries
- Python program to merge to dictionaries.
- How can we merge two Python dictionaries?
- How to merge two Python dictionaries in a single expression?
- How to merge multiple Python dictionaries?
- Python Program to Concatenate Two Dictionaries Into One
- Python Program to compare elements in two dictionaries
- Python Program to Merge two Tuples
- Python – Merge Dictionaries List with duplicate Keys
- Python Program to Merge Two Lists and Sort it
- Program to find largest merge of two strings in Python
- Program to merge two strings in alternating fashion in Python
- Java Program to Merge two lists
- Golang program to merge two slices
- Python - Intersect two dictionaries through keys

Advertisements