In Python, we usually deal with data structures like lists, tuples, and dictionaries. Nested data structures are when these data structures contain other data structures within them.
For example, consider a list of dictionaries. Each dictionary represents a person, and the list represents a group of people.
people = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30}
]
Here, people
is a nested data structure.
To access the data in nested structures, you chain the access methods. For a list of dictionaries like above, to access Bob's age, you'd do:
bob_age = people[1]["age"] # As Bob is the second item in the list (index 1) and age is a key in the dictionary.
You can also modify nested data structures. To change Bob's age, you'd do:
people[1]["age"] = 35
# A dictionary representing a student
student = {
"name": "Alice",
"grades": {"math": 90, "science": 85, "english": 88}
}
# Accessing Alice's math grade
math_grade = student["grades"]["math"]
print(math_grade) # Outputs: 90
# A list of lists, representing a matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Changing the value 6 to 60
matrix[1][2] = 60
print(matrix) # Outputs: [[1, 2, 3], [4, 5, 60], [7, 8, 9]]
In this tutorial, we've covered how to create, access, and manipulate nested data structures in Python. You should now feel comfortable working with complex data structures.
Try to use nested data structures in your programs. They are especially useful when working with large, complex data.
Create a dictionary representing a movie. The dictionary should contain title, year, and a list of actor names. Print the title and the first actor in the list.
Given a list of dictionaries, each representing a person with a name and age, write a function that prints the name of the oldest person.
Given a dictionary where each key is a student name and the value is a list of test scores, write a function that prints each student's highest score.