Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Dictionary setdefault() Method

Python3 Dictionary setdefault() Method

Python3 Dictionaries Python3 Dictionary


Description

The Python dictionary setdefault() method is similar to the get() method ; if the key is not in the dictionary, it adds the key and sets its value to the default.

Syntax

setdefault() method syntax:


dict.setdefault(key, default=None)

Parameters

Return Value

If key is in the dictionary, returns its value. If not, inserts key with the default value and returns default; default defaults to None.

Example

The following example shows how to use the setdefault() method:

Example

#!/usr/bin/python3

tinydict

= {

'

Name

'

:

'

Runoob

'

,

'

Age

'

:

7

}

print

(

"

Value of key Age: %s

"

%

tinydict

.

setdefault

(

'

Age

'

,

None

)

)

print

(

"

Value of key Sex: %s

"

%

tinydict

.

setdefault

(

'

Sex

'

,

None

)

)

print

(

"

The new dictionary is:

"

,

tinydict

)

The output of the above example is:


Age 键的值为 : 7
Sex 键的值为 : None
新字典为: {'Age': 7, 'Name': 'Runoob', 'Sex': None}

Python3 Dictionaries Python3 Dictionary