Accessing values using keys in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?"
Practice
'name' in the dictionary person = {'name': 'Alice', 'age': 30}?Solution
Step 1: Identify the dictionary and key
The dictionary ispersonand the key to access is'name'.Step 2: Use correct syntax to access value by key
In Python, dictionary values are accessed using square brackets and the key as a string:person['name'].Final Answer:
person['name'] -> Option CQuick Check:
Access value by key = person['name'] [OK]
- Using dot notation like person.name (not valid for dict)
- Using a value instead of key inside brackets
- Accessing a different key than asked
'city' from dictionary data without causing an error if the key does not exist?Solution
Step 1: Understand safe access in dictionaries
Usingdata['city']causes an error if the key is missing. Usingdata.get('city')returnsNoneinstead.Step 2: Identify correct method for safe access
Theget()method is designed to safely access keys without errors.Final Answer:
data.get('city') -> Option BQuick Check:
Safe key access = data.get('city') [OK]
- Using square brackets which raise KeyError if key missing
- Using dot notation which is invalid for dict
- Using wrong key case causing KeyError
info = {'a': 1, 'b': 2, 'c': 3}
print(info['b'])Solution
Step 1: Identify the dictionary and key accessed
The dictionaryinfohas key'b'with value2.Step 2: Access the value using the key
The code printsinfo['b'], which is2.Final Answer:
2 -> Option AQuick Check:
info['b'] = 2 [OK]
- Confusing key with value
- Expecting KeyError when key exists
- Mixing up keys and values
data = {'x': 10, 'y': 20}
print(data['z'])Solution
Step 1: Check if key exists in dictionary
The key'z'is not present indata.Step 2: Understand error caused by missing key
Accessing a missing key with square brackets raises aKeyError.Final Answer:
KeyError because 'z' is not in the dictionary -> Option DQuick Check:
Missing key access = KeyError [OK]
- Assuming missing keys return 0 or None
- Confusing syntax error with runtime error
- Using wrong bracket types
grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78}, which code snippet correctly prints Bob's grade or 'Not found' if Bob is not in the dictionary?Solution
Step 1: Understand the goal
We want to print Bob's grade if present, otherwise print 'Not found'.Step 2: Analyze each option
print(grades['Bob'] or 'Not found') will raise KeyError if key missing because access happens before 'or'. print(grades.get('Bob', 'Not found')) usesget()with default value, which is concise and safe. print(grades['bob'] or 'Not found') uses wrong key case and will fail. print(grades.get('Bob')) prints None if key missing, not 'Not found'.Final Answer:
print(grades.get('Bob', 'Not found')) -> Option AQuick Check:
Use get() with default for safe access [OK]
- Using wrong key case causing missing key
- Not providing default value in get()
- Assuming or operator works for missing keys
