What is usage of update method in Python dictionary?



The update() method of Python’s dictionary class serves two purposes.

It adds a new key-value pair if dictionary doesn’t already contain the key.

>>> d1={'name': 'Ravi', 'age': 25, 'marks': 60}

The update() method a dictionary object as argument

d1.update({"course":"ComputerEngg"})

The updated dictionary shows that a new key-value pair is added

>>> d1
{'name': 'Ravi', 'age': 25, 'marks': 60, 'course': 'Computer Engg'}

However, if the key as already present, its value is updated by the method

>>>d1.update({"age":21})
>>> d1
{'name': 'Ravi', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}



Advertisements