Python Dictionary update() method is “used to update the dictionary with the items from another dictionary object or an iterable of key/value pairs.”
Syntax
dict1.update(iterable)
Parameters
iterable(optional): A dictionary or an iterable object with key/value pairs.
Return Value
This method returns None; it just updates one dictionary with other dictionary objects or iterable keys/pairs.
Visual Representation
Example 1: How to Use Python Dictionary update
# Declaring two dictionaries
dict1 = {'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot'}
dict2 = {'Animal': 'Tiger', 'Tree': 'Coconut'}
# Printing dictionary1 and Dictionary2
print("Original dictionary1: " ,dict1)
print("Original dictionary2: " , dict2)
# Now we will update dict1 with the value of dict2
dict1.update(dict2)
# Now printing new values of dictionary1
print("Updated dictionary1: " ,dict1)
Output
Original dictionary1: {'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot'}
Original dictionary2: {'Animal': 'Tiger', 'Tree': 'Coconut'}
Updated dictionary1: {'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot',
'Animal': 'Tiger', 'Tree': 'Coconut'}
Example 2: Update a dictionary with an iterable
main_dict = {'Name': 'Krunal'}
print("Original dictionary:", main_dict)
main_dict.update(Rollno=21, College='VVP')
print("After updating a dictionary", main_dict)
Output
Original dictionary: {'Name': 'Krunal'}
After updating a dictionary {'Name': 'Krunal',
'Rollno': 21, 'College': 'VVP'}
Example 3: How to update the dictionary if a key exists
To update the value of a key in a dictionary, if the key exists in Python, you can use either dictionary.update() method or the assignment operator(=).
main_dict = {"Name": "Krunal", "Rollno": 21, "College": "VVP"}
print("Original dictionary:", main_dict)
if "Rollno" in main_dict:
main_dict.update(Rollno = 19)
print("After updating a dictionary", main_dict)
Output
Original dictionary: {'Name': 'Krunal', 'Rollno': 21, 'College': 'VVP'}
After updating a dictionary {'Name': 'Krunal', 'Rollno': 19, 'College': 'VVP'}
Example 4: update() When Tuple is Passed
dict = {'x': 21}
dict.update([('y', 31), ('z', 0)])
print(dict)
Output
{'x': 21, 'y': 31, 'z': 0}
That’s it.