English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
popitem() returns and deletes the last key-value pair from the dictionary.
If this method is called while the dictionary is already empty, a KeyError exception is thrown in 3.7 In earlier versions, the popitem() method deleted a random item.
The item deleted is the return value of the popitem() method, in the form of a tuple. See the following example.
The syntax of popitem() is:
dict.popitem()
popitem() does not accept any parameters.
popitem()
Return any element (key, value) pair from the dictionary
Delete any element from the dictionary (the returned element is the same).
Note: Any element and random element are not the same. popitem() does not return a random element.
person = {'name': 'Phill', 'age': 22, 'salary': 3500.0} result = person.popitem() print('person = ',person) print('result = ',result)
When running this program, the output is:
person = {'name': 'Phill', 'age': 22} result = ('salary', 3500.0)
If the dictionary is empty, popitem() will raise a KeyError error.