Python Dictionary popitem() Function: Guide

Python Dictionary popitem() Function Example

The popitem() function removes the last inserted item into the dictionary.

Python Dictionary popitem()

Python dictionary popitem() is a built-in method used to remove an arbitrary element from a dictionary. It will remove the key and value, which means an item from the dictionary. The popitem() method doesn’t take any parameter and removes and returns the arbitrary (key, value) pair as a 2-tuple.

If the popitem() is applied on an empty dictionary, a KeyError will be raised. In Python 3.7 before, the popitem() method removes the random element. The removed element is the return value of a popitem() method.




The dictionary popitem() method does not take any argument. Here, dict_name is the name of the dictionary.

Return Value

The popitem() method returns an arbitrary element (key and value) pair from the dictionary, removing that pair from the dictionary. The popitem() method returns a KeyError if the dictionary is empty.

Programming Example


# Declaring a dictionary
dict1 = {'Flower': 'Rose', 'Fruit': 'Apple',
         'Bird': 'Parrot', 'Animal': 'Tiger'}
# printing the dictionary
# Now we will call popitem() to remove an arbitary item
# popped item will be stored in item
item = dict1.popitem()
# Printing popped item
# printing the new dictionary
print("After pop new dictionary is: ")


{'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot', 'Animal': 'Tiger'}
('Animal', 'Tiger')
After pop new dictionary is:
{'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot'}

In this example, we can see that we have declared one dictionary and then printed the dictionary.

After that, we have called the popitem() method to remove one arbitrary element from the dictionary, and then we have stored it in the variable named item. After that, we have printed items and a new dictionary.

The popitem() method in the dictionary helps to achieve a similar purpose. It removes the arbitrary key-value pair from the dictionary and returns it as a tuple.

That’s it for this tutorial.

See also

Python dictionary items()

Python dictionary fromKeys()

Python dictionary keys()

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.