15. Understanding nested structures

Quiz: 0/5

Nested structures in Python allow us to combine data types like lists, dictionaries, and tuples to organize information efficiently. Think of them as containers within containers, like folders holding files or nested storage boxes. Let's explore:

Lists of Dictionaries

A list can hold multiple dictionaries, where each dictionary stores details about an item, person, or object. This is useful for organizing multiple records of similar data.

Imagine you’re tracking student information for a class. Each student has a dictionary of details, and all these dictionaries are stored in a list.

Example:

students = [
    {"name": "Alice", "age": 20},
    {"name": "Bob", "age": 22},
    {"name": "Charlie", "age": 23}
]

Here:

  • The list students contains three dictionaries.
  • Each dictionary represents a student’s information.

Accessing data:

print(students[0])  # Outputs: {'name': 'Alice', 'age': 20}
print(students[0]["name"])  # Outputs: Alice

Tuples within Lists

A tuple is a fixed, unchangeable collection of items. Combining tuples with lists helps you group related information while ensuring it stays unchanged.

Imagine you’re recording scores for students. Each record is a tuple with the student’s name and their score, stored inside a list.

Example:

scores = [
    ("Alice", 85),
    ("Bob", 90),
    ("Charlie", 88)
]

Here:

  • The list scores contains tuples.
  • Each tuple pairs a student’s name with their score.

Accessing data:

print(scores[1])  # Outputs: ('Bob', 90)
print(scores[1][1])  # Outputs: 90

Dictionaries containing Lists or other Dictionaries

A dictionary can hold lists or even other dictionaries as its values. This is powerful for organizing related data in a structured way.

Dictionaries containing Lists

You can group multiple related items in a list and associate it with a key in a dictionary.

Imagine you’re recording a student’s name and their scores across different exams.

Example:

student = {
    "name": "Alice",
    "scores": [85, 90, 78]
}

Here, the student dictionary contains a list under the "scores" key.

Accessing data:

print(student["name"])  # Outputs: Alice
print(student["scores"])  # Outputs: [85, 90, 78]
print(student["scores"][0])  # Outputs: 85

Dictionaries containing other Dictionaries

You can nest dictionaries inside another dictionary to represent hierarchical data.

Imagine you’re managing a school’s classes, where each class has a teacher and students.

Example:

school = {
    "class_1": {
        "teacher": "Mrs. Smith",
        "students": ["Alice", "Bob"]
    },
    "class_2": {
        "teacher": "Mr. Brown",
        "students": ["Charlie", "David"]
    }
}

Here:

  • The school dictionary contains dictionaries for each class.
  • Each class dictionary stores its teacher and a list of students.

Accessing data:

print(school["class_1"]["teacher"])  # Outputs: Mrs. Smith
print(school["class_1"]["students"][1])  # Outputs: Bob

Why are nested structures useful?

Nested structures reflect real-world relationships and make your data more organized. For example:

  • A shopping cart might have a list of product dictionaries.
  • A university system might store courses (dictionaries) with enrolled students (lists) and grades (tuples).

 

Hands-On Practise

Exercise: Managing a school database

Imagine you are building a small system to manage data for a school. You need to store information about multiple classes, students, and their scores.

Instructions:

  1. Create a List of Dictionaries for Multiple Classes: Each dictionary should represent one class. Each class will contain:

    • A "class_name" (string, e.g., "Math 101")
    • A "teacher" (string, e.g., "Mrs. Brown")
    • A "students" list, where each student is a tuple containing: The student’s name (string), the student’s age (integer) and a list of their scores (list of integers)
  2. Accessing and Modifying Data:

    • Print the name of the teacher for the first class.
    • Print the name and age of the second student in the third class.
    • Add a new score to the first student in the second class.

Tasks to complete:

  1. Print out the teacher’s name of the first class Math 101.
  2. Print the name and age of the second student in the third class Science 101.
  3. Add a new score to the first student in the second class History 101.
  4. Print out the updated student list for the second class after adding the score.
Output:

Quizzes: 0/5

Question 1:

What is the result of accessing school_data[1]['students'][0][2] in the given example?

  • The first student's name in the second class
  • The first student's age in the second class
  • The first student's scores in the second class
  • The second student's scores in the second class

Question 2:

Which Python data structure is used to store multiple pieces of information about a student, such as name, age, and scores?

  • List
  • Tuple
  • Dictionary
  • Set

Question 3:

What is the main purpose of using nested structures like lists of dictionaries in Python?

  • To store a single type of data
  • To create complex data models
  • To perform mathematical operations
  • To store unique elements only

Question 4:

Which of the following is the correct way to access the teacher of the first class in the given school_data example?

  • school_data[0]['teacher']
  • school_data[1]['teacher']
  • school_data[2]['teacher']
  • school_data[0]['students'][0]['teacher']

Question 5:

How would you modify the score of the second student in the first class in the provided school_data example?

  • school_data[0]['students'][1].append(100)
  • school_data[0]['students'][1][2].append(100)
  • school_data[0]['students'][1][2] = 100
  • school_data[0]['students'][1][2] = [100]

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonConversions between data structuresNext lessonFiltering and transforming Data with List Comprehensions