Accessing values using keys in Python - Time & Space Complexity
When we access values using keys in a dictionary, we want to know how long it takes as the dictionary grows.
We ask: How does the time to find a value change when the dictionary gets bigger?
Analyze the time complexity of the following code snippet.
my_dict = {i: i*2 for i in range(n)}
key_to_find = n - 1
value = my_dict[key_to_find]
print(value)
This code creates a dictionary with n items, then accesses a value by its key once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing a value by key in the dictionary.
- How many times: Exactly once.
Accessing a value by key takes about the same time no matter how big the dictionary is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays almost the same even if the dictionary grows larger.
Time Complexity: O(1)
This means accessing a value by its key takes about the same time no matter how many items are in the dictionary.
[X] Wrong: "Accessing a value by key takes longer as the dictionary gets bigger because it has to check many items."
[OK] Correct: Dictionaries use a special method to find keys quickly, so it does not check every item one by one.
Knowing that dictionary key access is fast helps you write efficient code and answer questions confidently in interviews.
"What if we tried to find a value by searching through all keys instead of using direct access? How would the time complexity change?"