Python Reference ยท Dictionaries and Sets
Python dict.pop() method
Reference for Python dict.pop(): remove a key and return its value, the optional default that avoids KeyError, and how it differs from del and popitem().
The dict.pop() method removes a key from a dictionary and returns the value that was stored under it. That makes it a "take it out and use it" operation, unlike del d[key], which removes the entry but gives you nothing back.
If the key is missing, pop() raises KeyError, unless you provide a default. With a default it returns that value and leaves the dictionary unchanged, which is a compact way to remove a key that may or may not exist.
d = {"a": 1, "b": 2} print(d.pop("a")) # 1 print(d) # {'b': 2}
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
dict.pop(key) dict.pop(key, default)
| Name | Description |
|---|---|
key |
The key to remove. |
default |
Optional. Returned if key is not in the dictionary. Any value is allowed, including None. |
Return value: the removed value, or default when the key was missing and a default was supplied.
Raises: KeyError if the key is missing and no default was given. TypeError if the key is not hashable.
Usage notes
- Changes the dictionary. The entry is gone afterwards, and the dictionary shrinks by one. If the key is missing and a default is passed, nothing changes.
- The default can be
None.d.pop(key, None)never raises and works for "remove if present". - Do not remove while iterating. Popping keys inside
for k in draisesRuntimeError. Iterate overlist(d)(a snapshot) instead. - Not the same as
list.pop(). For lists,pop()takes an index and defaults to the last item. For dictionaries, the argument is a key, and the key is required. - Use
popitem()to remove the most recently inserted pair without naming a key:dict.popitem(). - Use
delwhen you do not need the value and want an error for a missing key. - The default is evaluated eagerly, like any function argument, so avoid expensive expressions there.
- Positional-only.
d.pop(key="a")raisesTypeError. - Insertion order of the remaining keys is preserved.