Your phone contacts
Your phone has contacts. You do not look for the third contact. You type a name, and the phone gives you the number.
A dictionary is a data structure that works the same way. You give it a name. It gives you the matching value.
Key words
| Word | What it means | Example |
|---|---|---|
| Dictionary | A data structure that stores pairs. You look up a value by its key. | {"Sam": 16} |
| Key | The name you look up. Each key is different. | "Sam" |
| Value | The data stored with a key. | 16 |
| Pair | One key with its value. | "Sam": 16 |
| List | One name that holds many values in order. | [4, 8, 15] |
| Index | The position number in a list. It starts at 0. | 0 |
| Data structure | A way to organise many values. | list, dictionary |
The cells students fill in are left blank in this preview.
Try it: make a dictionary
ages = {"Sam": 16, "Aisha": 17, "Leo": 15}
print(ages)
print(ages["Aisha"])
print(len(ages))
# Look up Leo instead of Aisha.
The dictionary as a table
| Key | Value |
|---|---|
| "Sam" | 16 |
| "Aisha" | 17 |
| "Leo" | 15 |
The cells students fill in are left blank in this preview.
How it works
A dictionary stores pairs. Each pair is a key and a value, with a colon between them. The whole dictionary is inside curly brackets.
You find a value by its key, not by a number. Every key must be different.
Read the dictionary
Have a go
Read the dictionary
3 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.
What you can do with a dictionary
| Code | What it does | Result |
|---|---|---|
| menu["pie"] = 4 | Add a new pair, or change an old one | pie is now 4 |
| menu["tea"] | Read a value by its key | for example 2 |
| "tea" in menu | Is the key there? | True or False |
| "pie" not in menu | Is the key missing? | True or False |
| menu.pop("tea") | Remove the pair and give back its value | for example 2 |
| len(menu) | How many pairs? | for example 3 |
The cells students fill in are left blank in this preview.
Try it: change a dictionary
menu = {"tea": 2, "cake": 3}
menu["pie"] = 4
menu["tea"] = 2.5
print(menu)
print("cake" in menu)
print(menu.pop("cake"))
print(menu)
print(len(menu))
# Predict each line before you run it.
Try it: visit every pair
ages = {"Sam": 16, "Aisha": 17}
for name in ages:
print(name, "is", ages[name])
# The loop gives each key. ages[name] gives its value.