Dictionaries
In this tutorial, we'll store labelled values as key-value pairs.
A dictionary stores labelled values. Each label is called a key.
student = {
"name": "Ada",
"score": 95,
"passed": True,
}
Use dictionaries when you want to describe one thing with several pieces of information.
Reading Values
Use the key inside square brackets:
print(student["name"])
print(student["score"])
Output:
Ada
95
The key must match exactly. "Name" and "name" are different keys.
Updating Values
Dictionaries are mutable:
student["score"] = 98
student["grade"] = "A"
print(student)
This changes the score and adds a new key called "grade".
Using get()
If a key might be missing, get() is safer:
print(student.get("email"))
print(student.get("email", "No email saved"))
The second example gives a default value if "email" does not exist.
Looping Over a Dictionary
You can loop over keys and values:
for key, value in student.items():
print(key, value)
Common Mistake
Do not use a list when your data needs labels:
student = ["Ada", 95, True]
This works, but it is not clear what each position means. A dictionary is more readable.
Practice
Create a dictionary for a film with title, year, rating, and watched status. Print a sentence using at least two keys.