Dictionary use cases in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When using dictionaries in Python, it is important to understand how fast operations like adding, looking up, or removing items happen.
We want to know how the time to do these actions changes as the dictionary grows bigger.
Analyze the time complexity of the following code snippet.
my_dict = {}
for i in range(n):
my_dict[i] = i * 2
value = my_dict.get(5)
if 10 in my_dict:
del my_dict[10]
This code adds n items to a dictionary, then looks up a value, and finally deletes an item if it exists.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding items to the dictionary inside the loop.
- How many times: The loop runs n times, adding one item each time.
- Lookup and deletion happen once each, outside the loop.
As n grows, adding items takes more steps because we do it n times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions + 2 single operations |
| 100 | About 100 additions + 2 single operations |
| 1000 | About 1000 additions + 2 single operations |
Pattern observation: The total work grows roughly in direct proportion to n because each addition takes about the same time.
Time Complexity: O(n)
This means the time to add n items grows linearly with n, while lookups and deletions take about the same short time no matter the size.
[X] Wrong: "Looking up or deleting an item in a dictionary takes longer as the dictionary gets bigger."
[OK] Correct: Dictionaries use a special method that lets them find or remove items quickly, almost instantly, no matter how many items they hold.
Understanding how dictionary operations scale helps you write fast and efficient code, a skill that shows you know how to handle data well in real projects.
"What if we used a list instead of a dictionary for storing items? How would the time complexity for lookup change?"
Practice
dictionary in Python?Solution
Step 1: Understand dictionary structure
Dictionaries store data in pairs where each key maps to a value.Step 2: Identify dictionary use case
This structure allows fast lookup by key, unlike lists which use indexes.Final Answer:
To store data as key-value pairs for quick access -> Option AQuick Check:
Dictionaries = key-value pairs [OK]
- Confusing dictionaries with lists or sets
- Thinking dictionaries keep order like lists
- Assuming dictionaries store only numbers
my_dict?Solution
Step 1: Recall dictionary syntax for adding items
To add or update a key-value pair, use square brackets with the key and assign a value.Step 2: Check each option
Onlymy_dict['key'] = 'value'correctly adds or updates the dictionary.Final Answer:
my_dict['key'] = 'value' -> Option CQuick Check:
Use square brackets to add/update dict items [OK]
- Using list methods like append or insert on dictionaries
- Trying to use a non-existent add() method
- Confusing dictionary syntax with list syntax
my_dict = {'a': 1, 'b': 2}
my_dict['c'] = 3
print(my_dict)Solution
Step 1: Understand dictionary update
Addingmy_dict['c'] = 3adds a new key 'c' with value 3.Step 2: Print the updated dictionary
Printing shows all keys and values including the new one.Final Answer:
{'a': 1, 'b': 2, 'c': 3} -> Option DQuick Check:
Adding key updates dict content [OK]
- Expecting original dict without new key
- Thinking print shows only last added key
- Assuming error when adding new keys
my_dict = {'x': 10, 'y': 20}
print(my_dict['z'])Solution
Step 1: Check dictionary keys
Keys are 'x' and 'y', but 'z' is not present.Step 2: Accessing missing key causes error
Trying to printmy_dict['z']raises a KeyError.Final Answer:
KeyError because 'z' is not in the dictionary -> Option AQuick Check:
Access missing key = KeyError [OK]
- Assuming missing keys return 0 or None
- Confusing KeyError with SyntaxError
- Trying to use wrong bracket types
students = [('Alice', 85), ('Bob', 90), ('Alice', 95)]Which code correctly creates a dictionary with the latest score for each student?
Solution
Step 1: Understand dictionary comprehension behavior
When keys repeat, the last value overwrites earlier ones.Step 2: Check each option
scores = {name: score for name, score in students} uses comprehension that keeps the last score for 'Alice' (95). scores = dict(students) scores['Alice'] = 85 wrongly resets 'Alice' score. scores = {} for name, score in students: if name not in scores: scores[name] = score keeps only first score. scores = {name: max(score) for name, score in students} is invalid syntax.Final Answer:
scores = {name: score for name, score in students} -> Option BQuick Check:
Dict comprehension overwrites duplicate keys [OK]
- Assuming dict keeps first value for duplicates
- Using invalid syntax for max(score)
- Manually overwriting values incorrectly
