You called my_dict.pop("key") and Python crashed with KeyError. The fix is simple: my_dict.pop("key", None) returns None instead of raising. But there are subtleties around when to use which form, and how this differs from list.pop and set.discard.

📌 Quick answer: Use my_dict.pop("key", None) for safe removal. The second argument is the default returned when the key is missing. For sets use my_set.discard("item") (no-op if missing) or my_set.remove("item") (raises KeyError if missing).
Cause 1: Bare dict.pop on absent key
Default Python behavior: raises KeyError if the key is missing.
d = {"a": 1, "b": 2}
d.pop("c") # ❌ KeyError: 'c'
d.pop("c", None) # ✓ returns None
d.pop("c", "default") # ✓ returns "default"Cause 2: set.remove() vs set.discard()
set.remove() raises KeyError if missing (same behavior as dict.pop). set.discard() silently does nothing.
s = {1, 2, 3}
s.remove(4) # ❌ KeyError: 4
s.discard(4) # ✓ no-op, returns NoneCause 3: list.pop confusion (different exception)
list.pop raises IndexError, not KeyError, on out-of-range index.
lst = [1, 2, 3]
lst.pop(10) # ❌ IndexError: pop index out of range
# Safe pattern for lists
lst.pop() if lst else None # pop last if non-empty
lst.pop(10) if len(lst) > 10 else None # safe popping at indexPrevention
- Always pass a default to dict.pop unless missing means “fail loudly”
- Prefer set.discard() over set.remove() for forgiving removal
- For lists, guard with
if lstorif len(lst) > ibefore pop
Related Guides
Frequently Asked Questions
How do I safely pop a key from a dict in Python?
Use my_dict.pop(‘key’, None). The second argument is the default returned when the key is missing. Without it, dict.pop raises KeyError.
What’s the difference between set.remove() and set.discard()?
set.remove(item) raises KeyError if the item is missing. set.discard(item) silently does nothing. Use discard when you don’t care if the item was there; use remove when you do.
Why does list.pop() raise IndexError instead of KeyError?
Lists use position-based indexing, so out-of-range access is an IndexError, not KeyError. KeyError is for dict-style key lookups.
Can I pop multiple keys from a dict at once?
Not in one call. Use a loop: for k in keys: d.pop(k, None). Or filter into a new dict: d = {k: v for k, v in d.items() if k not in keys_to_remove}.
What does dict.popitem() do?
popitem() removes and returns an arbitrary (key, value) pair as a tuple. In Python 3.7+ it’s last-inserted (LIFO). Raises KeyError if the dict is empty. Use ‘if d: d.popitem()’ to guard.
