VOOZH about

URL: https://www.geeksforgeeks.org/python/python-dictionary-popitem-method/

⇱ Python Dictionary popitem() method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python Dictionary popitem() method

Last Updated : 11 Jul, 2025

popitem() method in Python is used to remove and return the last key-value pair from the dictionary. It is often used when we want to remove a random element, particularly when the dictionary is not ordered.

Example:


Output
(3, '011')
{1: '001', 2: '010'}

Explanation: In this example, the last key-value pair 3: '011' is removed from the dictionary and the updated dictionary is printed.

popitem() syntax

dict.popitem()

Here, dict is the dictionary from which the key-value pair is to be removed.

Parameter:

  • None: The popitem() method does not take any parameters.

Returns:

  • This method returns a tuple containing the last key-value pair removed from the dictionary.
  • If the dictionary is empty, it raises a KeyError.

popitem() examples

Example 1: popitem() on an Empty Dictionary


Output
'popitem(): dictionary is empty'

Explanation: When popitem() is called on an empty dictionary, it raises a KeyError indicating that the dictionary is empty.

Example 2: Removing Items One by One


Output
(3, '011')
(2, '010')
(1, '001')

Explanation: Here, we remove and print each item from the dictionary until it becomes empty. The items are removed in reverse insertion order.

Comment
Article Tags: