Python Dictionary setdefault() method
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
- key -- the key to look up.
- default -- the default value to set when the key does not exist.
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 Search
'
}
"
Value : %s
"
%
tinydict
.
setdefault
(
'
runoob
'
,
None
)
"
Value : %s
"
%
tinydict
.
setdefault
(
'
Taobao
'
,
'
Taobao
'
)
The output of the above example is:
Value : Runoob Tutorial
Value : 淘宝
Python Dictionary