Sub topic 1
Nesting Python Lists and Dictionaries
Prerequisites
You should know basic Python syntax, variables, for loops, functions, lists, and dictionaries. A list is an ordered, changeable collection. A dictionary is a collection of key-value pairs. Both can contain other lists or dictionaries.
Common ways to nest data
Nested data means placing one collection inside another. Common shapes include:
- A list of dictionaries:
[{"name": "Ana"}, {"name": "Ben"}] - A dictionary of lists:
{"colors": ["red", "blue"]} - A dictionary of dictionaries:
{"user": {"name": "Ana"}} - A list of lists:
[[1, 2], [3, 4]]
Choose a shape based on how you need to find the data. A list of dictionaries works well for records. A dictionary of lists works well for named groups.
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
print(students[1]["grades"][2]) # 92Reaching into nested data
Read one level at a time. Use an integer index for a list and a key for a dictionary. The expression students[1] selects Ben's dictionary. Adding ["grades"] selects his list. Adding [2] selects the third grade.
This is called chained indexing. Every step must match the type of the current value. Using a string key on a list raises TypeError; using a missing dictionary key raises KeyError.
Changing nested values in place
Lists and dictionaries are mutable, which means their contents can change after creation. Use chained indexing on the left side of an assignment to replace a value. Use list methods such as append() to add an item.
students[0]["grades"].append(95)
students[1]["grades"][0] = 75
print(students[0]["grades"]) # [90, 85, 95]
print(students[1]["grades"]) # [75, 88, 92]The variable students still refers to the same outer list. Only the selected nested values changed.
Exercise
What value does data["groups"][0][1] produce for data = {"groups": [["a", "b"], ["c", "d"]]}?
Show answer
It produces "b": the key selects the outer list, index 0 selects the first inner list, and index 1 selects its second item.