Python3 Dictionary get() Method
Description
The Python dictionary get() function returns the value of the specified key.
Syntax
get() method syntax:
dict.get(key[, value])
Parameters
- key -- the key to look up in the dictionary.
- value -- optional, the default value returned when the specified key does not exist.
Return Value
Returns the value of the specified key; if the key is not in the dictionary, returns the default value, or if no default is specified, returns None。
Example
The following example shows how to use the get() function:
Example
#!/usr/bin/python
tinydict
=
{
'Name'
:
'Runoob'
,
'Age'
:
27
}
(
"Age : "
,
tinydict.
get
(
'Age'
)
)
Sex is not set and no default value is given, so None is printed
(
"Sex : "
,
tinydict.
get
(
'Sex'
)
)
Salary is not set, so the default value 0.0 is printed
(
'Salary: '
,
tinydict.
get
(
'Salary'
,
0.0
)
)
The output of the above example is:
Age : 27
Sex : None
Salary: 0.0
Differences between the get() method and dict[key] access
The get(key) method can return a default value when the key is not in the dictionary None or the configured default value.
When the key is not in the dictionary, dict[key] raises KeyError exception.
Example
runoob
=
{
}
(
'URL: '
,
runoob.
get
(
'url'
)
)
Returns None
URL:
None
(
runoob
[
'url'
]
)
A KeyError is raised
Traceback
(
most recent call last
)
:
File
"
,
line
1
,
in
<
module
KeyError:
'url'
Usage with nested dictionaries
The get() method is used with nested dictionaries as follows:
Example
#!/usr/bin/python
tinydict
=
{
'RUNOOB'
:
{
'url'
:
'www.runoob.com'
}
}
res
=
tinydict.
get
(
'RUNOOB'
,
{
}
)
.
get
(
'url'
)
Output result
(
"RUNOOB url is: "
,
str
(
res
)
)
The output of the above example is:
RUNOOB url 为 : www.runoob.com
Python3 Dictionary