Python 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, or a default value if the key is not in the dictionary None or the configured default value.
Example
The following example shows how to use the get() function:
Example
#!/usr/bin/python
-- coding: UTF-8 --
tinydict
=
{
'Name'
:
'Runoob'
,
'Age'
:
27
}
(
"Age : %s"
% tinydict.
get
(
'Age'
)
)
Sex is not set and no default value is given, so None is printed
(
"Sex : %s"
% tinydict.
get
(
'Sex'
)
)
Salary is not set, so the default value 0.0 is printed
(
'Salary: %s'
% 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
-- coding: UTF-8 --
tinydict
=
{
'RUNOOB'
:
{
'url'
:
'www.runoob.com'
}
}
res
=
tinydict.
get
(
'RUNOOB'
,
{
}
)
.
get
(
'url'
)
Output result
(
"RUNOOB url is: %s"
%
str
(
res
)
)
<
p
The output of the above example is:
<
/p
<
preRUNOOB url is: www.
runoob
.
com
<
/pre
Python Dictionary