English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python dictionary popitem() usage and example

Python dictionary methods

popitem() returns and deletes the last key-value pair in the dictionary.
If the dictionary is already empty and this method is called, a KeyError exception is thrown in 3.7 In earlier versions, the popitem() method deleted a random item.

The deleted item 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() parameters

popitem() does not accept any parameters.

popitem() return value

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. 

Example: How does popitem() work?

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, calling popitem() will raise a KeyError error.

Python dictionary methods