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.