A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-dictionary-popitem-method/ below:

Python Dictionary popitem() method - GeeksforGeeks

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:

Python
d = {1: '001', 2: '010', 3: '011'}

# Using popitem() to remove and return the last item
res = d.popitem()
print(res)
print(d)

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:

Returns:

popitem() examples

Example 1: popitem() on an Empty Dictionary

Python
d = {}

# Trying to use popitem() on an empty dictionary
try:
    d.popitem()
except KeyError as e:
    print(e)

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

Python
d = {1: '001', 2: '010', 3: '011'}

# removing items one by one using popitem()
print(d.popitem())
print(d.popitem())
print(d.popitem())

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.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4