Python3 Dictionary setdefault() Method
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
- key -- the key to look up.
- default -- the default value to set when the key does not exist.
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
}
(
"
Value of key Age: %s
"
%
tinydict
.
setdefault
(
'
Age
'
,
None
)
)
(
"
Value of key Sex: %s
"
%
tinydict
.
setdefault
(
'
Sex
'
,
None
)
)
(
"
The new dictionary is:
"
,
tinydict
)
The output of the above example is:
Age 键的值为 : 7
Sex 键的值为 : None
新字典为: {'Age': 7, 'Name': 'Runoob', 'Sex': None}
Python3 Dictionary