Remove Items
Learn every way to remove items from a Python dictionary: pop(), popitem(), del, clear(), and dict comprehensions, with examples and gotchas.
Python dictionaries are mutable key-value stores, which means you can add, change, and remove entries at any time. This chapter covers every standard technique for removing items from a dictionary — pop(), popitem(), the del statement, clear(), and dictionary comprehensions — with practical notes on when each approach fits best and how to avoid common errors.
Quick comparison
| Technique | Removes | Returns | Raises on missing key |
|---|---|---|---|
dict.pop(key) | One key-value pair | The removed value | KeyError (unless default given) |
dict.pop(key, default) | One key-value pair | The removed value or default | Never |
dict.popitem() | Last inserted pair | (key, value) tuple | KeyError if dict is empty |
del dict[key] | One key-value pair | Nothing | KeyError |
dict.clear() | All pairs | Nothing | Never |
| Dict comprehension | Selective pairs | New dictionary | Never |
Removing a single item with pop()
dict.pop(key) removes the key-value pair for the given key and returns the value that was stored there. This makes it useful when you need the value for further processing after removing it.
Remove a key and capture its value
If the key does not exist, pop() raises a KeyError:
inventory = {'apples': 10}
inventory.pop('oranges') # KeyError: 'oranges'Using a default to avoid KeyError
Pass a second argument to pop() as a fallback value. When the key is absent, pop() returns the default instead of raising an error — the dictionary is left unchanged.
Safe removal with a default
inventory = {'apples': 10, 'cherries': 20}
removed = inventory.pop('oranges', 0)
print(removed) # 0
print(inventory) # {'apples': 10, 'cherries': 20}This pattern is a clean alternative to checking if key in dict before calling pop().
Removing the last inserted item with popitem()
dict.popitem() removes and returns the last inserted key-value pair as a (key, value) tuple. It was the primary tool for iterating and consuming a dictionary before Python 3.7 guaranteed insertion order.
Pop the last inserted item
scores = {'alice': 95, 'bob': 82, 'carol': 78}
last_item = scores.popitem()
print(last_item) # ('carol', 78)
print(scores) # {'alice': 95, 'bob': 82}popitem() raises a KeyError if the dictionary is empty. Use it when you want to process and consume all items one by one (stack-like), or when you only need to remove the most recently added entry.
Removing an item with del
The del statement removes a key-value pair by key without returning any value. Use it when you only need to delete the entry and have no interest in the removed value.
Delete a key with del
Like pop() without a default, del raises a KeyError if the key is missing:
del user['phone'] # KeyError: 'phone'del vs pop() — which to use?
- Use
delwhen you want to discard the item and never need its value. - Use
pop()when you need the removed value, or want a safe no-op when the key may be absent.
Removing all items with clear()
dict.clear() empties the dictionary in place, leaving an empty {}. The dictionary object itself still exists, so any other variable that references the same dict will also see an empty dict.
Clear all entries
config = {'host': 'localhost', 'port': 5432, 'debug': True}
config.clear()
print(config) # {}Compare this to reassigning config = {}: reassignment creates a new dictionary object and leaves any other references pointing to the old (still populated) one. clear() modifies the same object.
config = {'host': 'localhost', 'port': 5432}
alias = config # alias and config point to the same dict
config = {} # only config is updated; alias still has data
print(alias) # {'host': 'localhost', 'port': 5432}
config = {'host': 'localhost', 'port': 5432}
alias = config
config.clear() # modifies the shared object
print(alias) # {}Removing multiple specific keys
Python has no built-in method for removing multiple keys at once, but there are two idiomatic approaches.
Loop with pop()
settings = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
to_remove = ['b', 'd']
for key in to_remove:
settings.pop(key, None) # None default = safe even if key is absent
print(settings) # {'a': 1, 'c': 3}Dictionary comprehension
A dict comprehension builds a new dictionary that excludes the unwanted keys. This is preferable when you want to keep the original intact.
Filter a dictionary using comprehension
You can also filter by value rather than key:
scores = {'alice': 95, 'bob': 40, 'carol': 78, 'dan': 35}
passing = {name: score for name, score in scores.items() if score >= 50}
print(passing) # {'alice': 95, 'carol': 78}Removing items while looping — the common gotcha
Modifying a dictionary during iteration raises a RuntimeError in Python 3:
data = {'a': 1, 'b': 2, 'c': 3}
# This raises RuntimeError: dictionary changed size during iteration
for key in data:
if data[key] < 2:
del data[key]The safe pattern is to iterate over a copy of the keys:
data = {'a': 1, 'b': 2, 'c': 3}
for key in list(data): # list() snapshots the keys
if data[key] < 2:
del data[key]
print(data) # {'b': 2, 'c': 3}Alternatively, build a new dict with a comprehension (shown above in the comprehension section) — this is often the cleanest approach.
For more on safely iterating dictionaries, see Loop Dictionaries.
Choosing the right method
- Need the removed value? Use
pop(key). - Key might not exist? Use
pop(key, default)to avoid aKeyError. - Just deleting, no need for the value? Use
del dict[key]. - Remove the last inserted entry? Use
popitem(). - Wipe everything? Use
clear(). - Remove based on a condition / multiple keys? Use a dict comprehension or a
for key in list(dict)loop.