How to merge two dictionaries in python
Dictionary
A dictionary is a collection of key-value pairs or items that can be referred to using a key name.
In a dictionary…
-
Duplicate items are
, changeable, and do not allow duplicates.unordered items do not have a specific order -
Values can be of any data type and duplicated, whereas keys can’t be repeated and must be immutable.
-
Dictionary keys are case sensitive.
Two methods
update()method**method
Explanation
- First, we create a dictionary (
d1) with the values set as fruit names. - Then, we print that dictionary.
- Next, we initialize a variable (
d3) and give it the same value as the dictionary (d1). - Then, we create dictionary
d1with key values 4,5,6 and other fruits as values. - Next, we initialize a variable (
d4) and give it the dictionary (d2). - Next, the update method (
d1) with the values ofd2merge and the two dictionaries’ items are updated. - Next, we should print d1.
- Then, using the
updatemethod, we update d2 with values of d1, basically merging the two dictionary items as updated elements. - Next, we print d2.
- Then, we create a new variable (called new) and assign the dictionary with d3,d4 parameters using the exponential operator (basically we update with the methods from the
d3andd4dictionary). - Finally, we print the new variable.
Code
d1 = {1:"cucumber",2:"peas",3:"carrot"}print(d1)d3 = d1d2 = {4:"Pineapple",5:"Mango",6:"Apple"}d4 = d2d1.update(d2)print(d1)d2.update(d1)print(d2)new = {**d3,**d4}print(new)