![]() |
VOOZH | about |
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:
(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.
dict.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
'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
(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.