Nested dictionaries in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When working with nested dictionaries, it's important to know how the time to access or process data grows as the dictionary gets bigger.
We want to find out how the number of steps changes when we loop through nested dictionaries.
Analyze the time complexity of the following code snippet.
data = {
'a': {'x': 1, 'y': 2},
'b': {'x': 3, 'y': 4},
'c': {'x': 5, 'y': 6}
}
for outer_key in data:
for inner_key in data[outer_key]:
print(data[outer_key][inner_key])
This code loops through a dictionary where each value is another dictionary, printing all inner values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops over outer and inner dictionaries.
- How many times: Outer loop runs once per outer key; inner loop runs once per inner key for each outer key.
As the number of outer keys and inner keys grows, the total steps grow by multiplying these counts.
| Input Size (outer keys x inner keys) | Approx. Operations |
|---|---|
| 10 x 5 = 50 | About 50 steps |
| 100 x 5 = 500 | About 500 steps |
| 1000 x 5 = 5000 | About 5000 steps |
Pattern observation: The total work grows by multiplying the number of outer keys by the number of inner keys.
Time Complexity: O(n * m)
This means the time grows proportionally to the number of outer keys times the number of inner keys.
[X] Wrong: "The time grows only with the number of outer keys because the inner dictionaries are small."
[OK] Correct: Even if inner dictionaries are small, the total time depends on both outer and inner sizes multiplied together, so ignoring inner keys underestimates the time.
Understanding how nested loops over dictionaries affect time helps you explain your code clearly and reason about performance in real projects.
"What if the inner dictionaries had different sizes? How would that affect the time complexity?"
Practice
Example: {'person': {'name': 'Alice', 'age': 30}}Solution
Step 1: Understand dictionary structure
A dictionary stores key-value pairs. Nested means one value is itself a dictionary.Step 2: Analyze the example
In {'person': {'name': 'Alice', 'age': 30}}, the value for 'person' is another dictionary.Final Answer:
A dictionary inside another dictionary -> Option BQuick Check:
Nested dictionary = dictionary inside dictionary [OK]
- Confusing nested dictionary with list inside dictionary
- Thinking nested means only one key
- Assuming keys must be numbers
colors = {'shirt': {'color': 'blue', 'size': 'M'}}Solution
Step 1: Identify keys to reach 'blue'
'blue' is the value of 'color' inside the dictionary for key 'shirt'.Step 2: Use correct key order
Access outer key 'shirt' first, then inner key 'color': colors['shirt']['color'].Final Answer:
colors['shirt']['color'] -> Option CQuick Check:
Outer then inner keys = colors['shirt']['color'] [OK]
- Swapping the order of keys
- Trying to access keys that don't exist
- Using only one key for nested value
data = {'user': {'name': 'Bob', 'age': 25}}
print(data['user']['age'])Solution
Step 1: Access nested dictionary value
data['user'] gives {'name': 'Bob', 'age': 25}.Step 2: Access 'age' key inside nested dictionary
data['user']['age'] gives 25.Final Answer:
25 -> Option AQuick Check:
Nested key access returns 25 [OK]
- Printing the whole nested dictionary instead of value
- Using wrong key order
- Expecting string 'Bob' instead of age
info = {'book': {'title': 'Python 101', 'pages': 200}}
print(info['book']['author'])Solution
Step 1: Check keys in nested dictionary
info['book'] has keys 'title' and 'pages', but no 'author'.Step 2: Accessing missing key causes error
Trying info['book']['author'] raises KeyError because 'author' is missing.Final Answer:
KeyError because 'author' key does not exist -> Option DQuick Check:
Missing key access = KeyError [OK]
- Assuming missing keys return None
- Confusing KeyError with SyntaxError
- Thinking nested dictionary keys are always present
students = {
'Alice': {'math': 90, 'science': 85},
'Bob': {'math': 75, 'science': 95}
}Which code correctly adds a new subject 'english' with score 88 for Alice?
Solution
Step 1: Identify where to add new subject
We want to add 'english' score inside Alice's dictionary.Step 2: Add key-value pair inside nested dictionary
Use students['Alice']['english'] = 88 to add the new subject and score.Final Answer:
students['Alice']['english'] = 88 -> Option AQuick Check:
Add key inside nested dict = students['Alice']['english'] = 88 [OK]
- Replacing entire inner dictionary instead of adding key
- Adding key at wrong dictionary level
- Swapping keys order
