Removing dictionary entries in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we remove entries from a dictionary, we want to know how the time it takes changes as the dictionary grows.
We ask: How does removing items scale with the number of entries?
Analyze the time complexity of the following code snippet.
my_dict = {i: i*2 for i in range(n)}
for key in list(my_dict.keys()):
if key % 2 == 0:
del my_dict[key]
This code creates a dictionary with n entries and removes all entries with even keys.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over all keys in the dictionary.
- How many times: Exactly n times, once for each key.
- Secondary operation: Deleting entries from the dictionary inside the loop.
As the dictionary size grows, the number of operations grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and some deletions |
| 100 | About 100 checks and deletions |
| 1000 | About 1000 checks and deletions |
Pattern observation: The work grows directly with the number of entries; doubling entries roughly doubles the work.
Time Complexity: O(n)
This means the time to remove entries grows in a straight line with the number of items in the dictionary.
[X] Wrong: "Deleting items from a dictionary inside a loop is constant time and does not affect overall time."
[OK] Correct: Each deletion takes average constant time, and since deletions happen inside a loop over n items, the total time grows with n.
Understanding how dictionary operations scale helps you write efficient code and explain your choices clearly in interviews.
"What if we removed items without converting keys to a list first? How would the time complexity change?"
Practice
pop(key) method do when used on a Python dictionary?Solution
Step 1: Understand the pop method
Thepop(key)method removes the specified key from the dictionary and returns its value.Step 2: Compare with other methods
Unlikedel dict[key],popreturns the removed value.Final Answer:
Removes the key and returns its value -> Option AQuick Check:
pop(key) = remove key + return value [OK]
- Thinking pop only returns value without removal
- Confusing pop with del which doesn't return value
- Assuming pop deletes entire dictionary
'age' from dictionary person without returning its value?Solution
Step 1: Identify syntax for deletion without return
To remove a key without returning its value, usedel dict[key].Step 2: Check options
del person['age'] usesdel person['age'], which is correct syntax. Options C and D are invalid methods.Final Answer:
del person['age'] -> Option DQuick Check:
del dict[key] removes key without return [OK]
- Using pop when no return is needed
- Using non-existent methods like remove or delete
- Wrong syntax like person.delete('age')
data = {'a': 1, 'b': 2, 'c': 3}
value = data.pop('b')
print(value, data)Solution
Step 1: Use pop to remove key 'b'
Thepop('b')removes key 'b' and returns its value 2.Step 2: Print returned value and updated dictionary
After removal, dictionary is {'a': 1, 'c': 3}. Printing value and dict shows: 2 {'a': 1, 'c': 3}.Final Answer:
2 {'a': 1, 'c': 3} -> Option CQuick Check:
pop returns value and removes key [OK]
- Expecting original dict unchanged
- Thinking pop returns None
- Confusing pop with del which returns nothing
info = {'name': 'Alice', 'age': 30}
info.pop('gender')Solution
Step 1: Understand pop behavior without default
Callingpopon a missing key without a default raises aKeyError.Step 2: Check code
Since 'gender' is not ininfo,info.pop('gender')raisesKeyError.Final Answer:
KeyError -> Option BQuick Check:
pop missing key without default = KeyError [OK]
- Expecting None instead of error
- Thinking pop returns the key name
- Confusing with pop(key, default)
items = {'apple': 5, 'banana': 0, 'cherry': 7}, which code removes all entries with value 0 or less safely without errors?Solution
Step 1: Avoid modifying dict while iterating
Directly deleting keys while iterating causes runtime errors. Usinglist(items)copies keys safely.Step 2: Use pop to remove keys with value ≤ 0
Loop over copied keys, check value, and usepopto remove safely.Final Answer:
for k in list(items): if items[k] <= 0: items.pop(k) -> Option AQuick Check:
Iterate on list copy + pop keys safely [OK]
- Deleting keys directly while iterating causes error
- Using pop without copying keys list
- Removing only one key instead of all matching
