The popitem method
The popitem
method removes a key-value pair from the end of a dictionary, returning a tuple of the removed pair. We do not specify anything in the method parameter.
Syntax
list.popitem()
Example
Let's apply the popitem
method to our dictionary:
dct = {
'a': 1,
'b': 2,
'c': 3
}
print(dct.popitem())
print(dct)
Result of code execution:
('c', 3)
{'a': 1, 'b': 2}
Example
Now let's try applying the popitem
method to an empty dictionary:
dct = {}
print(dct.popitem())
print(dct)
Result of code execution:
KeyError: 'popitem(): dictionary is empty'