The values of a dictionary can be anything, including lists and other dictionaries. This lets you represent structured data, such as that of a form, a product or a user.
Values that are lists
student = {"name": "Ana", "grades": [8, 9, 7]}
print(student["grades"]) # [8, 9, 7]
print(student["grades"][0]) # 8
student["grades"].append(10)
print(sum(student["grades"]) / len(student["grades"])) # 8.5
Dictionaries inside dictionaries
To reach a nested piece of data you chain the brackets, from the outside in:
user = {
"name": "Ana",
"address": {"city": "Madrid", "zip": "28001"},
}
print(user["address"]["city"]) # Madrid
user["address"]["zip"] = "28002"
List of dictionaries
The most common structure in real programs: a list where each element is a dictionary with the same fields, like the rows of a table.
students = [
{"name": "Ana", "age": 20, "grade": 8},
{"name": "Luis", "age": 23, "grade": 6},
{"name": "Eva", "age": 21, "grade": 7},
]
print(students[1]["name"]) # Luis
for s in students:
print(f"{s['name']} is {s['age']} years old")
# Ana is 20 years old
# Luis is 23 years old
# Eva is 21 years old
Notice that inside an f-string with double quotes you use single quotes for the keys: s['name'].
Searching, filtering and calculating
# Average grade
total = 0
for s in students:
total += s["grade"]
print(total / len(students)) # 7.0
# Oldest student
oldest = students[0]
for s in students:
if s["age"] > oldest["age"]:
oldest = s
print(oldest["name"]) # Luis
# Passed
passed = []
for s in students:
if s["grade"] >= 7:
passed.append(s["name"])
print(passed) # ['Ana', 'Eva']
A dictionary of dictionaries
When each element has a unique identifier, it is convenient for that identifier to be the key. That way you look it up directly, without going through the whole list:
by_name = {
"ana": {"age": 20, "grade": 8},
"luis": {"age": 23, "grade": 6},
}
print(by_name["luis"]["grade"]) # 6
Copying with care
Assigning a dictionary to another variable does not copy it: both point to the same dictionary. To copy it use copy():
a = {"x": 1}
b = a
b["x"] = 99
print(a) # {'x': 99} (a changed too)
c = {"x": 1}
d = c.copy()
d["x"] = 99
print(c) # {'x': 1}
copy() is a shallow copy: nested dictionaries or lists are still shared.
Practice in Student records.