Python Tutorial
Python Remove Dictionary Items
pop() removes a named key. popitem() removes the last inserted item. del and clear() also work.
pop, popitem, del, clear
pop returns the value. del can delete one key or the whole dict.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.pop("model")
thisdict.popitem()
del thisdict["brand"]
print(thisdict)
thisdict.clear()📘 Real-World Deep Dive
Removing a key from a dict is one-line but choosing <code>del/pop/popitem/clear|={}</code> matters when the missing-key case matters, when you want a default back, or when you want to drain the dict.
Real-Life Scenario
A small session table that must purge expired entries (older than N seconds) on each call without rebuilding the structure.
Real-Life Example
import time
from typing import MutableMapping
class TimedMap(MutableMapping):
def __init__(self, ttl_seconds: float) -> None:
self._ttl = ttl_seconds
self._data: dict[str, tuple[float, object]] = {}
def __getitem__(self, k: str) -> object:
ts, v = self._data[k]
if time.monotonic() - ts <= self._ttl:
return v
del self._data[k] # drop expired entry on read
raise KeyError(k)
def __setitem__(self, k: str, v: object) -> None:
self._data[k] = (time.monotonic(), v)
def __delitem__(self, k: str) -> None:
del self._data[k]
def __iter__(self):
return iter(self._data)
def __len__(self) -> int:
return len(self._data)
def purge_expired(self) -> int:
now = time.monotonic()
expired = [k for k, (ts, _) in self._data.items() if now - ts > self._ttl]
for k in expired:
del self._data[k]
return len(expired)
m = TimedMap(ttl_seconds=0.05)
m["u1"] = "ada"
m["u2"] = "bo"
time.sleep(0.06)
print("count before purge:", len(m))
print("purged:", m.purge_expired())
print("count after purge :", len(m))Expected Output
count before purge: 2
purged: 2
count after purge : 0Common mistakes
del d[k]raisesKeyErroron a missing key;d.pop(k, default)is the safe variant.popitem()removes an arbitrary (in CPython, the last-inserted) key — do not assume an order.- Removing keys during iteration raises
RuntimeError— snapshot keys first or use a comprehension.
🚀 Performance & Best Practices
list(d.keys())creates a list for safe mutation; for O(1) work, iterate overlist(d).- Bulk deletions are faster as one comprehension than per-key
del. - If you only need a default value,
d.pop(k, default)beatsif k in d: del d[k]; else: ....
🧪 Try It Yourself
- Implement
drop_while(d, predicate)that removes keys whose value matches a predicate. - Add a
reset()method that swaps the underlying dict atomically. - For huge maps, switch to
diskcacheorsqlite3.