Python Dictionary popitem() Method

Removes a key-value pair from a dictionary

Usage

The popitem() method removes and returns the last inserted key:value pair from the dictionary. Pairs are returned in Last In First Out (LIFO) order.

In versions before 3.7, popitem() would remove and return a random item.

Syntax

dictionary.popitem()

Examples

# Remove the last inserted item from the dictionary
D = {'name': 'Bob', 'age': 25}
D.popitem()
print(D)
# Prints {'name': 'Bob'}

popitem() returns key:value pair of removed item as a tuple.

D = {'name': 'Bob', 'age': 25}
v = D.popitem()
print(v)
# Prints ('age', 25)

popitem() on Empty Dictionary

calling popitem() on an empty dictionary, raises a KeyError exception.

D = {}
D.popitem()
# Triggers KeyError: 'popitem(): dictionary is empty'

To avoid such exception, you must check if the dictionary is empty before calling the popitem() method.

D = {}
if D:
    D.popitem()