Python3 Dictionary popitem() Method
Description
The Python dictionary popitem() method returns and removes the last pair of key and value from the dictionary.
If the dictionary is already empty when this method is called, a KeyError exception is raised.
Syntax
popitem() method syntax:
popitem()
Parameters
- None
Return Value
Returns the last inserted key/value pair (in key, value form), following the LIFO (Last In First Out) rule, i.e. the last key/value pair.
**Note:** before Python 3.7, popitem() removed and returned an arbitrary key/value pair from the dictionary.
Example
The following example shows how to use the popitem() method:
Example
#!/usr/bin/python3
site
=
{
'name'
:
'Runoob Tutorial'
,
'alexa'
:
10000
,
'url'
:
'www.runoob.com'
}
('url': 'www.runoob.com') was inserted last, so it is removed
result
=
site
.
popitem
(
)
(
'Return value = '
,
result
)
(
'site = '
,
site
)
Insert a new element
site
[
'nickname'
]
=
'Runoob'
(
'site = '
,
site
)
Now ('nickname', 'Runoob') is the last inserted element
result
=
site
.
popitem
(
)
(
'Return value = '
,
result
)
(
'site = '
,
site
)
The output is:
返回值 = ('url', 'www.runoob.com')
site = {'name': 'Runoob Tutorial', 'alexa': 10000}
site = {'name': 'Runoob Tutorial', 'alexa': 10000, 'nickname': 'Runoob'}
返回值 = ('nickname', 'Runoob')
site = {'name': 'Runoob Tutorial', 'alexa': 10000}
Python3 Dictionary