Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

dict.pop

Removes a key and returns its previous value.

Version: Python 3.14; repository image, production runtime not attested

Syntax

m.pop(key[, default])

Removes a key and returns its previous value.

A supplied default handles a missing key without mutation. Without a default the same lookup raises KeyError.

The first lookup removes a and returns its stored value three. On the second lookup a is absent and the supplied fallback minus one is returned without inserting it. Without a fallback an absent key raises KeyError.

d = {"a": 0}
assert d.pop("a", 9) == 0 and d.pop("a", 9) == 9 and not d

Examples

m = {"a": 3}
print(m.pop("a"))
print(m.pop("a", -1))
print(m)

Result

3
-1
{}

The first lookup removes a and returns its stored value three. On the second lookup a is absent and the supplied fallback minus one is returned without inserting it. Without a fallback an absent key raises KeyError.

Sources