Python 3 reference · Dictionary Methods

Python Dictionary popitem() Method

Remove and return the last inserted (key, value) pair (LIFO order). Raises KeyError if the dict is empty.

Python 3 Since 3.0

Syntax

dict.popitem()

Return value

A (key, value) tuple.

Examples

Remove the newest itemTry it yourself
d = {"a": 1, "b": 2, "c": 3}
print(d.popitem(), d)

Output

('c', 3) {'a': 1, 'b': 2}
Drain a dictionaryTry it yourself
tasks = {"t1": "write", "t2": "test"}
while tasks:
    key, task = tasks.popitem()
    print(key, task)

Output

t2 test
t1 write

Version history

VersionChange
Python 3.0Added
Python 3.7Guaranteed to remove the last inserted item (LIFO).