Python Dictionary popitem() method
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:
d = {1: '001', 2: '010', 3: '011'}
# Using popitem() to remove and return the last item
res = d.popitem()
print(res)
print(d)
Output
(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() syntax
dict.popitem()
Here, dict
is the
dictionary from which the key-value pair is to be removed.
Parameter:
- None: The popitem() method does not take any parameters.
Returns:
- This method returns a tuple containing the last key-value pair removed from the dictionary.
- If the dictionary is empty, it raises a KeyError.
popitem() examples
Example 1: popitem() on an Empty Dictionary
d = {}
# Trying to use popitem() on an empty dictionary
try:
d.popitem()
except KeyError as e:
print(e)
Output
'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
d = {1: '001', 2: '010', 3: '011'}
# removing items one by one using popitem()
print(d.popitem())
print(d.popitem())
print(d.popitem())
Output
(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.