Python3 Dictionary popitem() Method
Description
The Python dictionary popitem() method randomly returns and removes the last key-value pair in the dictionary.
If the dictionary is already empty, calling this method will raise a KeyError exception.
Syntax
The syntax of the popitem() method is:
popitem()
Parameters
- None
Return Value
Returns the last inserted key-value pair (in key, value form) according to the LIFO (Last In First Out) order rule, i.e., the key-value pair at the very end.
Note:Before Python 3.7, the popitem() method removed and returned an arbitrary key-value pair from the dictionary.
Example
The following example demonstrates how to use the popitem() method:
Example
#!/usr/bin/python3
site= {'name': 'Example Tutorial', 'alexa': 10000, 'url': 'www.example.com'}
# ('url': 'www.example.com') the last inserted will be removed
result = site.popitem()
print('Return value = ', result)
print('site = ', site)
# Insert a new element
site['nickname'] = 'Example'
print('site = ', site)
# Now ('nickname', 'Example') is the last inserted element
result = site.popitem()
print('Return value = ', result)
print('site = ', site)
site= {'name': 'Example Tutorial', 'alexa': 10000, 'url': 'www.example.com'}
# ('url': 'www.example.com') the last inserted will be removed
result = site.popitem()
print('Return value = ', result)
print('site = ', site)
# Insert a new element
site['nickname'] = 'Example'
print('site = ', site)
# Now ('nickname', 'Example') is the last inserted element
result = site.popitem()
print('Return value = ', result)
print('site = ', site)
The output is:
返回值 = ('url', 'www.example.com')
site = {'name': 'Example', 'alexa': 10000}
site = {'name': 'Example', 'alexa': 10000, 'nickname': 'Example'}
返回值 = ('nickname', 'Example')
site = {'name': 'Example', 'alexa': 10000}
Other Extensions
Python3 Dictionary