Last Updated : 11 Jul, 2025
popitem() method in Python is used to remove and return the last key-value pair from the dictionary. It is often used when we want to remove a random element, particularly when the dictionary is not ordered.
Example:
Python
d = {1: '001', 2: '010', 3: '011'}
# Using popitem() to remove and return the last item
res = d.popitem()
print(res)
print(d)
(3, '011') {1: '001', 2: '010'}
Explanation: In this example, the last key-value pair 3: '011' is removed from the dictionary and the updated dictionary is printed.
popitem() syntaxdict.popitem()
Here, dict
is the
dictionary from which the key-value pair is to be removed.
Parameter:
Returns:
Example 1: popitem() on an Empty Dictionary
Python
d = {}
# Trying to use popitem() on an empty dictionary
try:
d.popitem()
except KeyError as e:
print(e)
'popitem(): dictionary is empty'
Explanation: When popitem() is called on an empty dictionary, it raises a KeyError indicating that the dictionary is empty.
Example 2: Removing Items One by One
Python
d = {1: '001', 2: '010', 3: '011'}
# removing items one by one using popitem()
print(d.popitem())
print(d.popitem())
print(d.popitem())
(3, '011') (2, '010') (1, '001')
Explanation: Here, we remove and print each item from the dictionary until it becomes empty. The items are removed in reverse insertion order.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4