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

Python Basic Tutorial

Python Flow Control

Fonctions en Python

Types de données en Python

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Usage and example of Python dictionary popitem()

Dictionary methods in Python

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

Dictionary methods in Python