Python Dictionary popitem() Method

The dict.popitem() method removes and returns a tuple of (key, value) pair from the dictionary. Pairs are returned in Last In First Out (LIFO) order.

Syntax:

dict.popitem()

Parameters:

No parameters.

Return Value:

Removes and returns the last inserted key-value pair in the dictionary.

The following example demonstrates the dict.popitem() method.

Example: Get Last Key-Value
romanNums = {'I':1, 'II':2, 'III':3 }
print(romanNums.popitem())
print(romanNums.popitem())
print(romanNums.popitem())
print(romanNums)
print(romanNums.popitem()) # throws error
Output
('III', 3)
('II', 2)
('I', 1)
{}
KeyError: 'popitem(): dictionary is empty'

In the above example, each call of romanNums.popitem() removes and returns a key-value pair. Calling the popitem() method on an empty dictionary will throw a KeyError.

Want to check how much you know Python?