update() method in Python Dictionary

If you have been following us along, then you would have noticed that we couldn’t make changes to the value of item through setdefault() method. The key and its associated value were already there. So, even if we tried through setdefault() for some other value then, it didn’t update. But, with update() method in Python dictionary – we can easily update items of a dictionary. In addition to, we can also update items from other dictionary as well.

Following is the syntax for update() method –

dictionary_name.update(iterable/dictionary_object)

where, iterable would be a key:value pair or we can also provide a dictionary object.

We cover more about it with relevant examples next.

update() method in Python Dictionary

Let’s say we have dictionary, x –

x = {"name":"abc", "age":24, "address":"xyz, qwerty"}

Example I. We start with the most easiest one, the item doesn’t yet exist in the dictionary. And, we use update() method to insert the item –

x.update({"new_key":"new_value"})

To view the outcome, use print() method –

print(x)

This would return with –

{'name': 'abc', 'age': 24, 'address': 'xyz, qwerty', 'new_key': 'new_value'}

The key:value pair was inserted through update() method.

Example II. We modify a value through update() method here –

x.update({"name":"new_value"})

Use print() method now –

print(x)

It returns with –

{'name': 'new_value', 'age': 24, 'address': 'xyz, qwerty'}

The value with associated key i.e. new_value replaces abc.

Example III. Here, we will see how to copy items from another dictionary, y –

y = {"new_key":"new_value", "otherk":"otherv"}

Now, to copy items from dictionary y to dictionary x –

x.update(y)

and, to view the changes –

print(x)

It returns with –

{'name': 'abc', 'age': 24, 'address': 'xyz, qwerty', 'new_key': 'new_value', 'otherk': 'otherv'}

Clearly, the items from dictionary y were copied to dictionary x.

In conclusion, we have discussed update() method in Python dictionary.

Similar Posts