English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Fonctions en Python

Types de données en Python

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python dictionary update() usage and examples

Python dictionary methods

The update() method inserts the specified items into the dictionary. This specified item can be a dictionary or an iterable object.

If the key is not in the dictionary, the update() method will add the element to the dictionary. If the key is in the dictionary, it will use the new value to update the key.

The syntax of update() is:

dict.update([other])

The parameters of update()

The update() method takesdictionaryor key/value pairs (usuallytupleThe iterable of the parameter

If update() is called without passing any parameters, the dictionary remains unchanged.

The return value of update() 

The update() method uses a dictionary object or a key/Elements in an iterable of value pairs update the dictionary.

It does not return any value (returns None).

Example1: how update() works in Python?

d = {1: 'one', 2: 'three'}
d1 = {2: 'two'}
# Update key=2value
d.update(d1)
print(d)
d1 = {3: 'three'}
# Use keys3Add elements
d.update(d1)
print(d)

When running this program, the output is:

{1: 'one', 2: 'two'}
{1: 'one', 2: 'two', 3: 'three'

Example2: how to use update() with Iterable?

d = {'x': 2}
d.update(y = 3, z = 0)
print(d)

When running this program, the output is:

{'x': 2, 'y': 3, 'z': 0}

Python dictionary methods