dict.pop()
Python · Dictionaries
Theory
.pop(key) removes key from a dictionary and returns its value, so you can delete and use the value in one step. With employee = {'name': 'Asha', 'salary': 65000}, salary = employee.pop('salary') gives salary = 65000 and leaves employee as {'name': 'Asha'}. If the key is missing it raises KeyError, unless you pass a default: employee.pop('bonus', 0) returns 0 and changes nothing.
Removal by key is O(1) on average, thanks to hashing. Compare it with del employee['salary'], which also removes the key but does not give the value back, and with popitem(), which removes and returns the most recently inserted (key, value) pair and is useful for processing a dict until it is empty. Never pop keys from a dict while looping over it directly; Python raises RuntimeError because the size changed. Loop over list(d) instead, or build a new dict with a comprehension.
Why we use it
Moving a field from one place to another, extracting a value before saving the rest, or consuming items from a work dict all need 'remove and give me the value'. pop() does exactly that, safely with a default.
When to use it
Use pop(key) when you need the removed value, pop(key, default) when the key may not exist, and del d[key] when you do not need the value. Use popitem() to remove the last inserted pair.
How it works
- Call employee.pop('salary')
- Hash 'salary' and look it up
- Is the key present? Yes: Remove the pair and return its value. No: Go to the default check.
- Was a default given? Yes: Return the default, dict unchanged. No: Raise KeyError.
- print(salary, employee) shows 65000 {'name': 'Asha'}
Syntax
dict.pop(key, default)Example
employee = {'name': 'Asha', 'salary': 65000}
salary = employee.pop('salary')
print(salary, employee)Key points
- Raises a KeyError if the key is missing and no default is given
- pop(key, default) returns the default safely
- Useful for "remove and use the value" in one step
- del d[key] removes without returning the value
- popitem() removes the most recently added pair