Python3 Dictionary pop() Method
Description
The Python dictionary pop() method removes the value corresponding to a key and returns it. If the key does not exist, it can optionally return a default value (if provided).
Syntax
pop() method syntax:
dict.pop(key, default)
Parameters
key: the key to remove.default(optional): the default value returned when the key does not exist. If no default is provided and the key does not exist, aKeyErrorexception.
Return Value
Returns the removed value:
- If both the
keyexists - removes the corresponding element from the dictionary - If both the
keydoes not exist - returns the specified default value - If both the
keydoes not exist and no default value is specified - raisesKeyErrorexception
Example
The following example shows how to use the pop() method:
Example
#!/usr/bin/python3
site
=
{
'name'
:
'Runoob Tutorial'
,
'alexa'
:
10000
,
'url'
:
'www.runoob.com'
}
element
=
site
.
pop
(
'name'
)
(
'The removed element is:'
,
element
)
(
'The dictionary is:'
,
site
)
The output is:
删除的元素为: Runoob Tutorial
字典为: {'alexa': 10000, 'url': 'www.runoob.com'}
Deleting a key that does not exist raises an exception:
Example
#!/usr/bin/python3
site
=
{
'name'
:
'Runoob Tutorial'
,
'alexa'
:
10000
,
'url'
:
'www.runoob.com'
}
element
=
site
.
pop
(
'nickname'
)
(
'The removed element is:'
,
element
)
(
'The dictionary is:'
,
site
)
The output is:
File "/Users/RUNOOB/runoob-test/test.py", line 5, in
element = site.pop('nickname')
KeyError: 'nickname'
You can set a default value to avoid the exception:
Example
#!/usr/bin/python3
site
=
{
'name'
:
'Runoob Tutorial'
,
'alexa'
:
10000
,
'url'
:
'www.runoob.com'
}
element
=
site
.
pop
(
'nickname'
,
'Nonexistent key'
)
(
'The removed element is:'
,
element
)
(
'The dictionary is:'
,
site
)
The output is:
删除的元素为: 不存在的 key
字典为: {'name': 'Runoob Tutorial', 'alexa': 10000, 'url': 'www.runoob.com'}
Python3 Dictionary