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

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operations

Python objects and classes

Python date and time

Python advanced knowledge

Python reference manual

Python dictionary update() usage and example

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])

update() parameters

The update() method takesDictionaryor key/Value pair (usuallyTuple)iterable object.

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

The update() return value 

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

It does not return any value (returns None).

Example1:update() how it works in Python?

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

When running the program, the output is:

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

Example2:update() how to use with Iterable?

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

When running the program, the output is:

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

Python dictionary methods