Skip to main content

update()

The update() function in Python dictionary methods is used to update a dictionary with elements from another dictionary or from an iterable of key-value pairs. It adds or modifies key-value pairs in the dictionary variable based on the input provided.

Parameter Values

Parameter Description
iterable

A dictionary or an iterable of key-value pairs to update the current dictionary with.

Return Values

The update() method from Dictionary returns None. It updates the dictionary in-place.

How to Use update() in Python

Example 1:

The update() method updates the dictionary with the key-value pairs from another dictionary or iterable object. If a key already exists in the original dictionary, its value will be updated with the new value.

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1)
# Output: {'a': 1, 'b': 3, 'c': 4}
Example 2:

When updating with an iterable object like a list of tuples, each tuple should contain a key-value pair to be added or updated in the dictionary.

dict1 = {'a': 1, 'b': 2}
updates = [('b', 3), ('c', 4)]
dict1.update(updates)
print(dict1)
# Output: {'a': 1, 'b': 3, 'c': 4}
Example 3:

If the key is not already present in the dictionary, update() method will add it to the dictionary with the corresponding value.

dict1 = {'a': 1, 'b': 2}
new_data = {'c': 3, 'd': 4}
dict1.update(new_data)
print(dict1)
# Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}