Nested dictionaries let you store information inside other dictionaries. This helps organize data like a folder inside another folder.
Nested dictionaries in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
my_dict = {
'key1': {
'nested_key1': 'value1',
'nested_key2': 'value2'
},
'key2': {
'nested_key3': 'value3'
}
}Each value in the main dictionary can be another dictionary.
You access nested values by using multiple keys, like my_dict['key1']['nested_key1'].
Examples
Python
person = {
'name': 'Alice',
'address': {
'city': 'Wonderland',
'zip': '12345'
}
}Python
inventory = {
'apple': {'price': 0.5, 'stock': 100},
'banana': {'price': 0.3, 'stock': 150}
}Sample Program
This program creates a nested dictionary for store items. It then prints the price of the book and the quantity of pens by accessing nested keys.
Python
store = {
'book': {
'price': 12.99,
'quantity': 5
},
'pen': {
'price': 1.5,
'quantity': 20
}
}
# Print the price of the book
print(f"Book price: ${store['book']['price']}")
# Print the quantity of pens
print(f"Pen quantity: {store['pen']['quantity']}")Important Notes
You can add or change nested dictionary values by using multiple keys, like store['book']['price'] = 15.99.
Be careful to check if keys exist before accessing nested dictionaries to avoid errors.
Summary
Nested dictionaries help organize complex data by storing dictionaries inside dictionaries.
Access nested values using multiple keys in sequence.
They are useful for grouping related information together clearly.
Practice
1. What is a nested dictionary in Python?
Example: {'person': {'name': 'Alice', 'age': 30}}easy
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]
Hint: Look for a dictionary as a value inside another dictionary [OK]
Common Mistakes:
- Confusing nested dictionary with list inside dictionary
- Thinking nested means only one key
- Assuming keys must be numbers
2. Which of the following is the correct way to access the value 'blue' in this nested dictionary?
colors = {'shirt': {'color': 'blue', 'size': 'M'}}easy
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]
Hint: Use outer key first, then inner key in square brackets [OK]
Common Mistakes:
- Swapping the order of keys
- Trying to access keys that don't exist
- Using only one key for nested value
3. What will be the output of this code?
data = {'user': {'name': 'Bob', 'age': 25}}
print(data['user']['age'])medium
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]
Hint: Access keys step-by-step to get nested value [OK]
Common Mistakes:
- Printing the whole nested dictionary instead of value
- Using wrong key order
- Expecting string 'Bob' instead of age
4. Find the error in this code snippet:
info = {'book': {'title': 'Python 101', 'pages': 200}}
print(info['book']['author'])medium
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]
Hint: Check if key exists before accessing nested dictionary [OK]
Common Mistakes:
- Assuming missing keys return None
- Confusing KeyError with SyntaxError
- Thinking nested dictionary keys are always present
5. Given this nested dictionary:
Which code correctly adds a new subject 'english' with score 88 for Alice?
students = {
'Alice': {'math': 90, 'science': 85},
'Bob': {'math': 75, 'science': 95}
}Which code correctly adds a new subject 'english' with score 88 for Alice?
hard
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]
Hint: Add new key inside inner dictionary using outer then inner keys [OK]
Common Mistakes:
- Replacing entire inner dictionary instead of adding key
- Adding key at wrong dictionary level
- Swapping keys order
