Removing multiple keys from a dictionary safely
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
To remove multiple keys from a Python dictionary safely (without raising KeyError for missing keys), use dictionary comprehension to create a new dict excluding the unwanted keys, or use dict.pop(key, None) in a loop to remove keys in place. The "safely" part means handling keys that may not exist in the dictionary. This article covers all common approaches — comprehension, pop(), del with checks, and set operations — with their tradeoffs in readability, performance, and whether they modify the original dictionary or create a new one.
Method 1: Dictionary Comprehension (New Dict)
Create a new dictionary excluding the unwanted keys:
Using a set for keys_to_remove gives O(1) lookup per key, making this O(n) overall where n is the dictionary size.
Method 2: pop() in a Loop (In-Place)
dict.pop(key, default) removes a key and returns its value, or returns default if the key does not exist:
This modifies the dictionary in place and is O(k) where k is the number of keys to remove.
Method 3: del with Key Check (In-Place)
Functionally identical to pop() but uses del instead. Slightly less concise since it requires an explicit if check.
Method 4: Set Difference on Keys (New Dict)
Use set arithmetic to compute the keys to keep:
dict.keys() returns a set-like view, so - computes the set difference directly.
Method 5: Using a Helper Function
Method 6: Keeping Only Specified Keys
Sometimes it is easier to specify which keys to keep rather than which to remove:
Performance Comparison
| Method | Creates New Dict? | Safe for Missing Keys? | Complexity |
| Comprehension | Yes | Yes | O(n) |
pop() loop | No (in-place) | Yes | O(k) |
del with check | No (in-place) | Yes | O(k) |
| Set difference | Yes | Yes | O(n) |
Common Pitfalls
- Using
del data[key]without checking existence:delraisesKeyErrorif the key does not exist. Always useif key in data: del data[key]or preferdata.pop(key, None)which handles missing keys silently. - Iterating over the dictionary while modifying it:
for key in data: del data[key]raisesRuntimeError: dictionary changed size during iteration. Iterate over a separate list of keys to remove, not over the dictionary itself. - Using a list instead of a set for keys_to_remove: With a list, the
if k not in keys_to_removecheck is O(k) per lookup, making comprehension O(n*k). Using a set makes it O(1) per lookup, keeping overall complexity at O(n). - Assuming comprehension modifies the original dict: Dictionary comprehension creates a new dictionary. If other variables reference the original dict, they still see the old data. Use
pop()ordelfor in-place modification when references matter. - Not considering
Noneas a valid dictionary value:data.pop(key, None)returnsNonefor both missing keys and keys whose value isNone. If you need to distinguish these cases, checkkey in databefore popping.
Summary
- Use
{k: v for k, v in d.items() if k not in keys_set}to create a new dict excluding specific keys - Use
d.pop(key, None)in a loop for safe in-place removal (noKeyErroron missing keys) - Convert
keys_to_removeto asetfor O(1) membership testing - Never modify a dictionary while iterating over it — iterate over a separate collection of keys
- Choose comprehension (new dict) vs
pop()(in-place) based on whether you need the original dict to change
Related reading
- Removing object from array in Swift 3
- Removing viewcontrollers from navigation stack
- Rename a dictionary key
- Reorder vector using a vector of indices
- Rename multiple files in a directory in Python
- Rename Pandas DataFrame Index
- Reordering a list to maximize difference of adjacent elements
- Reordering of array elements

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.