Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Preview

Dictionaries: look it up by name

This is the first page of the lesson. Read it and have a go at the activities. The rest is in the full lesson.

45 minutes

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

WordWhat it meansExample
DictionaryA data structure that stores pairs. You look up a value by its key.{"Sam": 16}
KeyThe name you look up. Each key is different."Sam"
ValueThe data stored with a key.16
PairOne key with its value."Sam": 16
ListOne name that holds many values in order.[4, 8, 15]
IndexThe position number in a list. It starts at 0.0
Data structureA way to organise many values.list, dictionary

The cells students fill in are left blank in this preview.

Try it: make a dictionary

Code: python
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

KeyValue
"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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your answers are marked here and are not kept. A college account keeps every student’s marks.

What you can do with a dictionary

CodeWhat it doesResult
menu["pie"] = 4Add a new pair, or change an old onepie is now 4
menu["tea"]Read a value by its keyfor example 2
"tea" in menuIs the key there?True or False
"pie" not in menuIs the key missing?True or False
menu.pop("tea")Remove the pair and give back its valuefor 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

Code: python
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

Code: python
ages = {"Sam": 16, "Aisha": 17}

for name in ages:
    print(name, "is", ages[name])

# The loop gives each key. ages[name] gives its value.

The lesson goes on

7 more parts of this lesson are in the full curriculum, with the tasks, the final check and the labs. A college account gives your students all of it.