Skip to main content

popitem()

The popitem() method in Python is a dictionary method that removes and returns an arbitrary key-value pair from a dictionary. This method is useful when you want to remove and process items from the dictionary in an arbitrary order.

Parameter Values

This function does not accept any parameters.

Return Values

The popitem() method returns a tuple with the key-value pair ((key, value)).

How to Use popitem() in Python

Example 1:

The popitem() method removes and returns an arbitrary key-value pair from the dictionary.

d = {'a': 1, 'b': 2, 'c': 3}
item = d.popitem()
print(item)
Example 2:

When called on an empty dictionary, popitem() raises a KeyError.

empty_dict = {}
try:
    item = empty_dict.popitem()
except KeyError as e:
    print('Dictionary is empty:', e)
Example 3:

The method can be used to implement LIFO functionality in a dictionary.

d = {'apple': 3, 'banana': 2, 'cherry': 1}
while d:
    key, value = d.popitem()
    print(f'Eating {key} ({value} left)')