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
dict.popitem
Removes and returns the last inserted (key, value) pair as a 2-tuple in LIFO order. Raises KeyError if the dictionary is empty.
dict.get
Returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None so this method never raises a KeyError.
dict.clear
Removes all items from the dictionary in place, leaving it empty. Returns None.
dict.update
Updates the dictionary in place with key/value pairs from other, overwriting existing keys. Accepts another mapping, an iterable of key/value pairs, and/or keyword arguments; returns None.
dict[key] = value
Assigns value to key using bracket subscription syntax, invoking __setitem__ under the hood. Creates the entry if key is absent, or overwrites the existing value; preserves the original insertion order when the key already exists.
← All Python dict methods · String methods · Built-in functions