mutation

dict.pop

Removes the specified key and returns its value. If the key is missing, returns default if provided; otherwise raises KeyError.

d.pop(key[, default])

Parameters

Parameter Purpose
key Key to remove from the dictionary
default Value returned when key is missing (suppresses KeyError)

Examples

>>> d = {'a': 1, 'b': 2}
>>> d.pop('a')
1
>>> d
{'b': 2}

Removes and returns the value

>>> d = {'a': 1}
>>> d.pop('missing')
Traceback (most recent call last):
  ...
KeyError: 'missing'

Without a default, missing key raises KeyError

>>> d = {'a': 1}
>>> d.pop('missing', None)
>>> d.pop('missing', 0)
0

Supply a default (even None) to make pop non-raising

>>> config = {'debug': True, 'port': 8080}
>>> debug = config.pop('debug', False)
>>> debug, config
(True, {'port': 8080})

Extract-and-remove pattern for config parsing

Gotcha

Without a default, pop raises KeyError on missing keys — pass a default (even None) to make it safe. Unlike list.pop, dict.pop requires a key argument.

Related methods

← All Python dict methods · String methods · Built-in functions