Python Glossary Русский

all Python 3Dictionaries (dict)function

dict.popitem

removal

Remove and return the last inserted (key, value) pair (LIFO since 3.7); KeyError if empty.

Syntax

d.popitem()

LIFO here means a stack: popitem() hands back the most recently inserted pair, not the oldest one; for FIFO reach for collections.OrderedDict with popitem(last=False), or a deque. It is also the safe way to drain a dict in a while d loop, since deleting keys while iterating over the dict itself raises RuntimeError about the size changing.

Examples

d = {'a': 1, 'b': 2}
print(d.popitem())   # → ('b', 2)
print(d)             # → {'a': 1}

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy