Bird
Raised Fist0
Pythonprogramming~10 mins

Nested dictionaries in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Nested dictionaries
Start: Create outer dictionary
Add key with inner dictionary
Access outer key
Access inner dictionary
Access inner key's value
Use or modify value
End
We create a dictionary that holds another dictionary as a value, then access keys step-by-step inside both dictionaries.
Execution Sample
Python
person = {
    "name": "Alice",
    "contact": {"email": "alice@example.com", "phone": "123-456"}
}
print(person["contact"]["email"])
This code creates a nested dictionary for a person and prints the email from the inner dictionary.
Execution Table
StepActionDictionary StateAccess/Output
1Create outer dictionary with keys 'name' and 'contact'{"name": "Alice", "contact": {"email": "alice@example.com", "phone": "123-456"}}N/A
2Access outer key 'contact'{"name": "Alice", "contact": {"email": "alice@example.com", "phone": "123-456"}}{"email": "alice@example.com", "phone": "123-456"}
3Access inner key 'email' inside 'contact'{"name": "Alice", "contact": {"email": "alice@example.com", "phone": "123-456"}}"alice@example.com"
4Print the accessed email value{"name": "Alice", "contact": {"email": "alice@example.com", "phone": "123-456"}}alice@example.com
💡 Finished accessing nested dictionary and printed the email value.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
personundefined{"name": "Alice", "contact": {"email": "alice@example.com", "phone": "123-456"}}{"name": "Alice", "contact": {"email": "alice@example.com", "phone": "123-456"}}{"name": "Alice", "contact": {"email": "alice@example.com", "phone": "123-456"}}{"name": "Alice", "contact": {"email": "alice@example.com", "phone": "123-456"}}
Key Moments - 2 Insights
Why do we use two sets of square brackets to access the email?
The first bracket accesses the outer dictionary's 'contact' key which holds another dictionary. The second bracket accesses the 'email' key inside that inner dictionary, as shown in execution_table steps 2 and 3.
Can we access 'email' directly from the outer dictionary?
No, because 'email' is inside the nested dictionary under 'contact'. You must first access 'contact' then 'email', as shown in the step-by-step access in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of person after Step 1?
A"alice@example.com"
B{"name": "Alice", "contact": {"email": "alice@example.com", "phone": "123-456"}}
C{"email": "alice@example.com", "phone": "123-456"}
Dundefined
💡 Hint
Check the 'Dictionary State' column at Step 1 in the execution_table.
At which step do we get the inner dictionary as the access result?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the 'Access/Output' column in the execution_table to find when the inner dictionary is accessed.
If we tried to access person["email"] directly, what would happen?
AIt would return "alice@example.com"
BIt would return None
CIt would cause a KeyError
DIt would return the whole nested dictionary
💡 Hint
Recall that 'email' is not a key in the outer dictionary, only inside the nested one, so direct access fails.
Concept Snapshot
Nested dictionaries store dictionaries inside dictionaries.
Access with multiple brackets: outer[key1][key2].
First get inner dictionary, then inner value.
Useful for structured data like contacts or settings.
Always check keys exist to avoid errors.
Full Transcript
This lesson shows how nested dictionaries work in Python. We start by creating an outer dictionary named 'person' with keys 'name' and 'contact'. The 'contact' key holds another dictionary with 'email' and 'phone'. We access the nested 'email' by first getting 'contact' from 'person', then 'email' from that inner dictionary. The execution table traces each step, showing the dictionary state and what is accessed or printed. Key moments clarify why two brackets are needed and why direct access to inner keys from the outer dictionary fails. The quiz tests understanding of dictionary states and access steps. The snapshot summarizes the concept for quick review.

Practice

(1/5)
1. What is a nested dictionary in Python?
Example: {'person': {'name': 'Alice', 'age': 30}}
easy
A. A dictionary with only one key
B. A dictionary inside another dictionary
C. A list inside a dictionary
D. A dictionary with numeric keys only

Solution

  1. Step 1: Understand dictionary structure

    A dictionary stores key-value pairs. Nested means one value is itself a dictionary.
  2. Step 2: Analyze the example

    In {'person': {'name': 'Alice', 'age': 30}}, the value for 'person' is another dictionary.
  3. Final Answer:

    A dictionary inside another dictionary -> Option B
  4. Quick 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
A. colors['shirt']['size']
B. colors['color']['shirt']
C. colors['shirt']['color']
D. colors['color']

Solution

  1. Step 1: Identify keys to reach 'blue'

    'blue' is the value of 'color' inside the dictionary for key 'shirt'.
  2. Step 2: Use correct key order

    Access outer key 'shirt' first, then inner key 'color': colors['shirt']['color'].
  3. Final Answer:

    colors['shirt']['color'] -> Option C
  4. Quick 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
A. 25
B. Bob
C. {'name': 'Bob', 'age': 25}
D. KeyError

Solution

  1. Step 1: Access nested dictionary value

    data['user'] gives {'name': 'Bob', 'age': 25}.
  2. Step 2: Access 'age' key inside nested dictionary

    data['user']['age'] gives 25.
  3. Final Answer:

    25 -> Option A
  4. Quick 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
A. No error, prints None
B. SyntaxError due to missing colon
C. TypeError because 'book' is not a dictionary
D. KeyError because 'author' key does not exist

Solution

  1. Step 1: Check keys in nested dictionary

    info['book'] has keys 'title' and 'pages', but no 'author'.
  2. Step 2: Accessing missing key causes error

    Trying info['book']['author'] raises KeyError because 'author' is missing.
  3. Final Answer:

    KeyError because 'author' key does not exist -> Option D
  4. Quick 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:
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
A. students['Alice']['english'] = 88
B. students['english']['Alice'] = 88
C. students['Alice'] = {'english': 88}
D. students['english'] = {'Alice': 88}

Solution

  1. Step 1: Identify where to add new subject

    We want to add 'english' score inside Alice's dictionary.
  2. Step 2: Add key-value pair inside nested dictionary

    Use students['Alice']['english'] = 88 to add the new subject and score.
  3. Final Answer:

    students['Alice']['english'] = 88 -> Option A
  4. Quick 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