The update() function in python updates the dictionary from an iterable of key/value pairs or with the elements from another dictionary object. If the key is not in the dictionary it inserts the elements into the dictionary, and if the key is in the dictionary it updates the key with the new value.
dict.update([other]) #where other may be iterable object generally tuples
The update() function takes a single parameter. If the function is called without passing parameters, the dictionary remains unchanged.
Parameter | Description | Required / Optional |
---|---|---|
other | A dictionary or an iterable object with key-value pairs, that will be inserted into the dictionary | Required |
The update() function returns none. This function just updates the dictionary with key/value pairs or inserts a new key value into the dictionary.
x = {5: "five", 6: "one"}
y = {6: "six"}
# updates the value of key 6
x.update(y)
print(x)
y = {7: "seven"}
# adds element with key 7
x.update(y)
print(x)
Output:
{5: 'five', 6: 'six'} {5: 'five', 6: 'six', 7: 'seven'}
t = {'a': 1}
t.update(b = 2, c = 3)
print(t)
Output:
{'a': 1, 'b': 2, 'c': 3}