Python Dictionary update() Method
The update()
method updates a dictionary with key-value pairs from another dictionary or an iterable of key-value pairs. If a key already exists, its value is updated; otherwise, a new key-value pair is added.
Syntax
dictionary.update([other])
Parameters
other
(Optional): A dictionary or an iterable of key-value pairs (e.g. list of tuples). If the method is called without any arguments, the dictionary remains unchanged.
Return Value
The update()
method modifies the dictionary in place and doesn’t return anything (meaning returns None
).
Example 1: Updating with another dictionary
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4}
The value of key b
is updated from 2
to 3
.
The key c
with value 4
is added to dict1
.
Example 2: Updating with an iterable of key-value pairs
dict1 = {'a': 1, 'b': 2}
dict1.update([('b', 3), ('c', 4)])
print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4}
Example 3: Updating with keyword arguments
person = {"name": "James", "age": 35}
person.update(age=40, city="Miami")
print(person)
Output:
{'name': 'James', 'age': 40, 'city': 'Miami'}
When to use update()
You can use update()
method to merge dictionaries or add multiple key-value pairs to the dictionary.