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

Python Dictionary setdefault() method

Python Dictionary setdefault() method

Python Dictionary Python Dictionary


Description

The Python Dictionary setdefault() function and 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 the dictionary contains the given key, the value corresponding to that key is returned; otherwise, the value set for that key is returned.

Example

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

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

tinydict

= {

'

runoob

'

:

'

Runoob Tutorial

'

,

'

google

'

:

'

Google Search

'

}

print

"

Value : %s

"

%

tinydict

.

setdefault

(

'

runoob

'

,

None

)

print

"

Value : %s

"

%

tinydict

.

setdefault

(

'

Taobao

'

,

'

Taobao

'

)

The output of the above example is:


Value : Runoob Tutorial
Value : 淘宝

Python Dictionary Python Dictionary