Python Dictionary popitem()
The popitem()
method removes and returns the last inserted key-value pair from a dictionary as a tuple.
Before Python 3.7, dictionaries didn’t preserve the insertion order, so popitem()
method removed and returned a random key-value pair.
Syntax
dict.popitem()
Parameters
It doesn’t take any parameters.
Return Value
It returns a tuple containing the last inserted key-value pair from the dictionary.
Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
removed_item = my_dict.popitem()
print(removed_item) # Output: ('c', 3)
print(my_dict) # Output: {'a': 1, 'b': 2}
Example with an empty dictionary
If the dictionary is empty, calling popitem()
raises a KeyError
.
my_dict = {}
removed_item = my_dict.popitem()
print(removed_item) # Raises KeyError
Handling KeyError
You can easily handle KeyError
using the try-except
block.
my_dict = {}
try:
removed_item = my_dict.popitem()
print(removed_item)
except KeyError as e:
print("Error: ", e)
# Output: Error: 'popitem(): dictionary is empty'
pop()
vs popitem()
The pop()
method removes a specific item by its key.
The popitem()
method removes the last inserted item as a tuple. (Removes a random item in Python versions before 3.7).