Computer >> Computer tutorials >  >> Programming >> Python

How to update a Python dictionary values?


Python’s in-built dictionary class has update() method. It takes another dictionary object as argument.

Example

D1.update(D2)

D2 object is merged with D1. If D2 contains key that is already present in D1, its value is updated and if it is a new key, a new key-value pair is added. D1 will show updated contents.

Output

>>> D1={"pen":25, "pencil":10, "book":100, "sharpner":5, "eraser":5}
>>> D2={"book":200, "scale":10}
>>> D1.update(D2)
>>> D1
{'pen': 25, 'pencil': 10, 'book': 200, 'sharpner': 5, 'eraser': 5, 'scale': 10}