Back
+10 XP
Concept

Deleting Keys: `.pop()` & `del`

`del d[key]` permanently removes a key. `d.pop(key)` removes the key and hands you the value that was stored there.

python
cache = {"auth": "token123", "temp": 42}
del cache["temp"]          # Deleted directly
token = cache.pop("auth")  # Removed and returned
print(cache)               # {}

# 82. Deleting Keys: `.pop()` & `del` `del d[key]` permanently removes a key. `d.pop(key)` removes the key and hands you the value that was stored there: ```python cache = {"auth": "token123", "temp": 42} del cache["temp"] # Deleted directly token = cache.pop("auth") # Removed and returned print(cache) # {} ``` Caution: If you call `del d["ghost"]` on a key that doesn't exist, Python will crash with a `KeyError`. Always check if it exists or use `d.pop("ghost", None)`.

Checkpoint

Which method removes a key from a dictionary and hands you its value?

Practice

Remove the key `"trash"` from `inventory = {"gold": 50, "trash": 1}` using `del`. Print `inventory`.

Terminal
01
Tap code blocks below to assemble
Available Blocks