2. Nested access
The value stored under a key can be another dictionary or a list. To reach a value inside it, chain one bracket per level:
Read the expression from left to right: user["address"] returns the inner dictionary, and the next ["city"] reads the key inside it. A list inside a dictionary works like any list: user["grades"][0] is the first grade.
Each key (or index) must exist at its level, or Python raises KeyError for a missing key or IndexError for a list index outside its range.
Read inside a nested dictionary
Create this dictionary:
Print the city using two keys in a row.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read a list inside a dictionary
Create team = {"members": ["Ada", "Grace", "Linus"]}. Print the second member using the key and then the list index 1.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read the last grade
Create student = {"name": "Ada", "grades": [7, 8, 9]}. Print the last grade using the key and the list index -1.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read three levels deep
Create data = {"a": {"b": {"c": 42}}}. Print the value 42 by chaining one key per level.
Print exactly:
Create a free account to save your progress and unlock chapter 2.