Using Dictionaries to Represent Single and Multiple Items

In Python, a dictionary represents one item (e.g., one student). To store multiple such items, we use a list of dictionaries.

Examples

One Dictionary for One Student

student = {
    "name": "Alice",
    "age": 21,
    "major": "Computer Science"
}
print(student["name"])
print(student["major"])
Alice
Computer Science

List of Dictionaries for Multiple Students

students = [
    {"name": "Alice", "age": 21, "major": "CS"},
    {"name": "Bob", "age": 22, "major": "Math"},
    {"name": "Cara", "age": 20, "major": "Biology"}
]

# Accessing second student's major
print(students[1]["major"])
Math

Looping Through a List of Dictionaries

for student in students:
    print(student["name"], "is studying", student["major"])
Alice is studying CS
Bob is studying Math
Cara is studying Biology

Exercise

  • Add a new student to the students list.
  • Print each student’s name and age.
  • Try changing a student’s major.
new_student = {"name": "Kate", "age": 21, "major": "Computer Science"}
students.append(new_student)

for student in students:
    print(f"{student['name']} is {student['age']} years old.")

for student in students:
    if student["name"] == "Bob":
        student["major"] = "Political Science"

print(students)
Alice is 21 years old.
Bob is 22 years old.
Cara is 20 years old.
Kate is 21 years old.
[{'name': 'Alice', 'age': 21, 'major': 'CS'}, {'name': 'Bob', 'age': 22, 'major': 'Political Science'}, {'name': 'Cara', 'age': 20, 'major': 'Biology'}, {'name': 'Kate', 'age': 21, 'major': 'Computer Science'}]