Python Function Reference

dict.popitem

Remove the most recently added pair from the dictionary and return it.

Python 3.13
dict.popitem()

Return value

A (key, value) tuple; raises KeyError for an empty dictionary.

Examples

Removing the last pair

Python 3.13
a = {'x': 1, 'y': 2}
print(a.popitem())
print(a)
('y', 2)
{'x': 1}

Emptying a dictionary from the end

Python 3.13
steps = {'first': 1, 'second': 2, 'third': 3}
while steps:
    print(steps.popitem())
('third', 3)
('second', 2)
('first', 1)

Details

Pairs are removed in the reverse order of insertion.

See also