Home » Python Dictionary update() method with Examples

Python Dictionary update() method with Examples

by Online Tutorials Library

Python Dictionary update() Method

Python update() method updates the dictionary with the key and value pairs. It inserts key/value if it is not present. It updates key/value if it is already present in the dictionary.

It also allows an iterable of key/value pairs to update the dictionary. like: update(a=10,b=20) etc.

Signature and examples of this method are given below.

Signature

Parameters

other: It is a list of key/value pairs.

Return

It returns None.

Let?s see some examples of update() method to understand it?s functionality.

Python Dictionary update() Method Example 1

It is a simple example to update the dictionary by passing key/value pair. This method updates the dictionary. See an example below.

Output:

Inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000}  Updated inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 50}  

Python Dictionary update() Method Example 2

If element (key/value) pair is already presents in the dictionary, it will overwrite it. See an example below.

Output:

Inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 50}  Updated inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 50}  Updated inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 150}  

Python Dictionary update() Method Example 3

The update() method also allows iterable key/value pairs as parameter. See, the example below two values are passed to the dictionary and it is updated.

Output:

Inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000}  Updated inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 50, 'switches': 1000}  

Next TopicPython Dictionary

You may also like