Delete items from a Python dictionary

Use del, pop, or popitem to remove dictionary entries, choose missing-key behavior, and delete several keys without mutating an active iteration.

Best practices
Python programming and application logging

Use del mapping[key] when the key must exist, or mapping.pop(key, default) when an absent key is acceptable. popitem() removes and returns the most recently inserted remaining pair in Python 3.7 and later.

Delete by key

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

A missing key raises KeyError. That can be useful when absence indicates a bug rather than a condition to ignore.

Remove and return a value

This is a separate example with fresh input:

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

The second argument is returned if the key is absent. Without it, pop() raises KeyError. A default of None cannot distinguish a missing key from a key that held None; use a unique sentinel object if that distinction matters.

Remove the last inserted pair

values = {"a": 1, "b": 2, "c": 3}
print(values.popitem())  # ('c', 3)

An empty dictionary raises KeyError. Updating an existing key's value does not make it the newest inserted key; deleting and reinserting it does.

Remove several items

Iterate over a separate key collection:

values = {"a": 1, "b": 2, "c": 3}
for key in ["a", "b"]:
    values.pop(key, None)

To remove by value, collect the keys first:

target = 3
keys_to_remove = [key for key, value in values.items() if value == target]
for key in keys_to_remove:
    del values[key]

Adding or deleting entries while iterating over the same dictionary or its views can raise RuntimeError or make iteration incomplete. A separate list avoids that size-change problem.

FAQ

Is del faster than pop()? Choose based on whether you need a return value and how absence should behave. Hash-table lookup is generally efficient, but a blanket constant-time guarantee ignores collisions and user-defined hashing or equality.

How do I empty the dictionary? values.clear() changes the existing dictionary, so other references see it become empty. values = {} rebinds only that name; other references still point to the old dictionary.

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