Python Dictionary pop() Method
Description
The Python Dictionary pop() method removes the value corresponding to the given key in the dictionary and returns the removed value.
Syntax
Syntax of the pop() method:
pop(key[,default])
Parameters
- key - The key to remove
- default - The value to return when the key does not exist
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/python
-- coding: UTF-8 --
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
Dictionary is:
{'url': 'www.runoob.com', 'alexa': 10000}
Deleting a key that does not exist raises an exception:
Example
#!/usr/bin/python
-- coding: UTF-8 --
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:
Traceback (most recent call last):
File "test.py", line 6, in
element = site.pop('nickname')
KeyError: 'nickname'
You can set a default value to avoid the exception:
Example
#!/usr/bin/python
-- coding: UTF-8 --
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:
The deleted elements are:
不存在的 key
Dictionary is:
{'url': 'www.runoob.com', 'alexa': 10000, 'name': '\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'}
Python Dictionary