Remove a key from a Python dictionary

Choose del or pop for dictionary deletion, distinguish a missing key from a stored None, and remove multiple entries without mutating an active iterator.

Best practices
Python programming and application logging

Use del mapping[key] when the key must exist. Use mapping.pop(key, default) when you want the removed value or want to handle a missing key without raising an exception.

Delete a required key

values = {"a": 1, "b": 2, "c": 3}
del values["b"]
print(values)  # {'a': 1, 'c': 3}

Deleting a missing key raises KeyError. That may be exactly what you want if absence indicates a bug. For optional deletion, a default passed to pop is more direct than checking membership first.

Remove and return the value

values = {"a": 1, "b": 2, "c": 3}
removed = values.pop("b")        # 2
missing = values.pop("x", None)  # None

Without a default, pop also raises KeyError for a missing key. If None is a valid stored value and you need to distinguish it from absence, use a unique sentinel:

sentinel = object()
result = values.pop("x", sentinel)
if result is sentinel:
    print("The key was absent")

Remove several entries

keys_to_remove = {"a", "b"}
for key in keys_to_remove:
    values.pop(key, None)

Alternatively, build a filtered dictionary:

remaining = {
    key: value for key, value in values.items()
    if key not in keys_to_remove
}

The loop mutates the original dictionary, so other references see the deletion. The comprehension creates a new dictionary and leaves the original unchanged unless you explicitly replace your reference to it.

Avoid changing size during iteration

To remove negative values in place, iterate over a snapshot of the keys:

values = {"a": -1, "b": 2, "c": -3}
for key in list(values):
    if values[key] < 0:
        del values[key]

Deleting keys while iterating directly over the dictionary can raise RuntimeError or make iteration unreliable. A snapshot or comprehension avoids that structural change to the active iterator.

FAQ

Can I remove keys by prefix? For string keys, use {k: v for k, v in values.items() if not k.startswith("tmp_")}. Mixed key types need an explicit policy before calling string methods.

Which method is faster? Choose based on whether you need a return value and how missing keys should behave. Typical hash-table deletion is expected constant time, but this is not a worst-case guarantee or a reason to assume identical timings.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting