Python dictionary Method - update()
The update()
method is a dictionary method in Python that updates a dictionary with the key-value pairs from another dictionary, or with an iterable of key-value pairs.
The syntax for using update()
is as follows:
dict.update([other])
The method takes one argument: other
. other
can be another dictionary or an iterable of key-value pairs.
If other
is a dictionary, the update()
method adds the key-value pairs from the other
dictionary to the calling dictionary. If a key already exists in the calling dictionary, the value for that key is updated with the value from other
.
If other
is an iterable of key-value pairs, each pair is treated as a separate key-value pair to be added to the calling dictionary.
Here is an example that demonstrates the use of update()
:
>>> d1 = {'a': 1, 'b': 2} >>> d2 = {'b': 3, 'c': 4} >>> d1.update(d2) >>> print(d1) {'a': 1, 'b': 3, 'c': 4}
In this example, the update()
method is used to update the dictionary d1
with the key-value pairs from d2
. The key 'b'
is present in both d1
and d2
, so its value in d1
is updated to 3
to match the value in d2
. The resulting dictionary is {'a': 1, 'b': 3, 'c': 4}
.
Here is another example that uses an iterable of key-value pairs:
>>> d = {'a': 1, 'b': 2} >>> d.update([('b', 3), ('c', 4)]) >>> print(d) {'a': 1, 'b': 3, 'c': 4}
In this example, the update()
method is used to update the dictionary d
with an iterable of key-value pairs. The key 'b'
is present in both d
and the iterable, so its value in d
is updated to 3
. The key 'c'
is not present in d
, so it is added with the value 4
. The resulting dictionary is {'a': 1, 'b': 3, 'c': 4}
.
In summary, update()
provides a way to update a dictionary with the key-value pairs from another dictionary or an iterable of key-value pairs. It can be useful in cases where you want to combine the contents of two or more dictionaries, or to add multiple key-value pairs to a dictionary at once.