= {
student "name": "Alice",
"age": 21,
"major": "Computer Science"
}print(student["name"])
print(student["major"])
Alice
Computer Science
In Python, a dictionary represents one item (e.g., one student). To store multiple such items, we use a list of dictionaries.
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
Alice is studying CS
Bob is studying Math
Cara is studying Biology
Exercise
students
list.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'}]