update() method in Python dictionary is used to add new key-value pairs or modify existing ones using another dictionary, iterable of pairs or keyword arguments. If a key already exists, its value is replaced. If the key does not exist, it is added to the dictionary.
Example: In this example, another dictionary is used to update existing keys and add new keys.
d = {'A': 1, 'B': 2}
d.update({'B': 5, 'C': 7})
print(d)
Output
{'A': 1, 'B': 5, 'C': 7}
Explanation: d.update({'B': 5, 'C': 7}) replaces value of 'B' and adds 'C'.
Syntax
dict.update([other])
- Parameters: other - Dictionary, iterable of key-value pairs, or keyword arguments.
- Returns: Does not return anything. It updates the dictionary.
Examples
Example 1: In this example, new key-value pairs are added to the dictionary.
d = {'x': 10}
d.update({'y': 20})
print(d)
Output
{'x': 10, 'y': 20}
Explanation: update({'y': 20}) adds new key 'y'.
Example 2: In this example, the value of an existing key is modified.
d = {'a': 5, 'b': 8}
d.update({'a': 50})
print(d)
Output
{'a': 50, 'b': 8}
Explanation: update({'a': 50}) replaces old value of 'a'.
Example 3: In this example, keyword arguments are used instead of another dictionary.
d = {'p': 1}
d.update(q=2, r=3)
print(d)
Output
{'p': 1, 'q': 2, 'r': 3}
Explanation: update(q=2, r=3) adds keys using keywords.