Home / Python / Reference / Dictionary methods

Python dictionary pop() method

Remove a key and return its value.

Syntax

dict.pop(key, default)

Raises KeyError for a missing key unless you give a default.

Parameters

keythe key to remove
defaultreturned if the key is missing

Return value

the removed value

Example

Code

cart = {"tea": 2, "cake": 1}
n = cart.pop("cake")
print(n, cart)
print(cart.pop("juice", 0))

Output

1 {'tea': 2}
0

Related

Learn it step by step in the free lesson Dictionaries & Sets, with exercises that check your answers.