The update() method updates the dictionary with the key-value pairs from the other dictionary. However, If the same key is present in the source dictionary, it overwrites the existing keys with the new value. In other words, it adds non-repeating key-value pairs and overwrites the value of duplicate keys.’
Update Dict in Python:
Method signature
The signature for the update() method is as shown below. Here, d1 refers to the source dictionary, and d2 represents the dictionary from where we are updating the key-value pair.
d1.update(d2)
Method parameters and return type
- The update() method takes one dictionary as a parameter.
- However, it doesn’t return anything.
Python Dictionary update Examples:
Example 1:
In this case, let us take a dictionary referred to as d1 with numbers assigned to colour names. Furthermore, d2 is also a dictionary with some numbers and color names. Now, we have to merge the dictionary’s content into a single one. However, if there is any repetition in the key, the update method will overwrite the value in d1 with new value in d2.
#Initializing
d1={1:"Red",2:"Blue",3:"Green"}
d2={4:"Pink",5:"Orange",3:"Yellow"}
#Printing
print("Before update Dictionary d1 is ",d1)
# Using update method
d1.update(d2)
#Printing
print("After update Dictionary d1 is ",d1)
Output
Before update Dictionary d1 is {1: 'Red', 2: 'Blue', 3: 'Green'}
After update Dictionary d1 is {1: 'Red', 2: 'Blue', 3: 'Yellow', 4: 'Pink', 5: 'Orange'}
Example 2:
Let us take two dictionaries with numbers assigned to city names in this example. Here, If we update the first dictionary with the content of the second one, then all the non-repeated keys are added, whereas duplicate keys overwrite the values.
#Initializing
d1={1:"Delhi",2:"Chennai",3:"Hyderabad"}
d2={1:"Bengaluru",2:"Bhopal",4:"Mumbai"}
#Printing
print("Before update Dictionary d1 is ",d1)
# Using update method
d1.update(d2)
#Printing
print("After update Dictionary d1 is ",d1)
Output
Before update Dictionary d1 is {1: 'Delhi', 2: 'Chennai', 3: 'Hyderabad'}
After update Dictionary d1 is {1: 'Bengaluru', 2: 'Bhopal', 3: 'Hyderabad', 4: 'Mumbai'}
Example 3:
We will take a dictionary with the department name and student name in this case. There is a key comp in dictionary d2, but it will be added as a new key-value pair due to the case difference.
#Initializing
d1={"Comp":"Jim","IT":"Tom","EXTC":"Siya"}
d2={"comp":"Sim","IT":"Philip"}
#Printing
print("Before update Dictionary d1 is ",d1)
# Using update method
d1.update(d2)
#Printing
print("After update Dictionary d1 is ",d1)
Output
Before update Dictionary d1 is {'Comp': 'Jim', 'IT': 'Tom', 'EXTC': 'Siya'}
After update Dictionary d1 is {'Comp': 'Jim', 'IT': 'Philip', 'EXTC': 'Siya', 'comp': 'Sim'}
Conclusion
The update() method updates the content of the current dictionary with the one passed as a parameter. For duplicate keys, it overwrites the old value with the new value.
References
Happy Learning 🙂