Python Dictionary popitem() Method



The Python dictionary popitem() method is used to remove and return an arbitrary key-value pair from the dictionary. It modifies the dictionary in place.

It works in the following way −

  • When you call popitem(), it removes and returns an arbitrary key-value pair as a tuple.
  • If the dictionary is empty, calling popitem() raises a KeyError.
  • If the dictionary is not empty, popitem() removes and returns a key-value pair. Which pair it removes is not guaranteed and may vary between Python implementations or versions. However, in Python 3.7 and later versions, it generally removes the last key-value pair that was added to the dictionary.
  • The method is useful when you want to remove and process items from a dictionary in an arbitrary order.

Syntax

Following is the basic syntax of the Python Dictionary popitem() method −

dictionary.popitem()

Parameters

This method does not accept any parameter.

Return Value

The method returns a tuple containing the key-value pair that was removed from the dictionary. The order of items in a dictionary is not guaranteed, so the key-value pair returned may be arbitrary.

Example 1

In the following example, we remove an arbitrary key-value pair from the dictionary "my_dict" and retrieve it as a tuple (key, value) −

my_dict = {'a': 1, 'b': 2, 'c': 3}
item = my_dict.popitem()
print("The item is:",item)  
print("The dictionary obtained is:",my_dict)   

Output

The output obtained is as follows −

The item is: ('c', 3)
The dictionary obtained is: {'a': 1, 'b': 2}

Example 2

Here, we demonstrate that the popitem() method usually removes the last item added to the dictionary. However, the order of iteration over dictionary items is not guaranteed before Python 3.7. −

my_dict = {'a': 1, 'b': 2, 'c': 3}
item = my_dict.popitem()
print("The item is:",item)  

Output

Following is the output of the above code −

The item is: ('c', 3)

Example 3

In this example, we remove an arbitrary key-value pair from the dictionary "my_dict" and assign its key and value to variables "key" and "value" −

my_dict = {'a': 1, 'b': 2, 'c': 3}
key, value = my_dict.popitem()
print("The key-value pair obtained is:",key, value)     

Output

The result produced is as shown below −

The key-value pair obtained is: c 3

Example 4

Now, we try to remove an arbitrary key-value pair from an empty dictionary, which raises a KeyError because there are no items to pop −

my_dict = {}
item = my_dict.popitem()

Output

We get the output as shown below −

Traceback (most recent call last):
  File "/home/cg/root/660e6943bb2bb/main.py", line 2, in <module>
item = my_dict.popitem()
KeyError: 'popitem(): dictionary is empty'
python_dictionary_methods.htm
Advertisements