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

Example: Remove the last inserted item from the dictionary

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

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

Example:

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

popitem() on Empty Dictionary

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

Example:

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

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

Example:

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