โ†Previous page

09SUPERPOWERS ยท DICTIONARIES

Boxes with labels.

A list keeps things in order: first, second, third. A dictionary keeps each thing with a label, so you find it by name, like backpack["pencils"].

IN REAL LIFE

Labels in real life.

You look for the label, and next to it is the value.

A real dictionary

You look up a word and find what it means. Word, then meaning.

The class phone list

Next to each name is a phone number. Name, then number.

A menu

Next to each food is its price. Food, then price.

LOOK FIRST

Key, colon, value.

Curly brackets

A dictionary goes inside { }. Each pair is key: value. The label is called a key.

Find by key

backpack["pencils"] gives back the value with that key.

Change or add

backpack["pencils"] = 5 changes the value. A new key adds a new pair.

STEP BY STEP

PyBot packs a backpack.

Keys in quotes, values after the colon.

backpack = {"pencils": 3, "books": 2}A dictionary with two keys: pencils keeps 3, books keeps 2.
print(backpack["pencils"])Find by key: shows 3
backpack["pencils"] = 5Change the value: now pencils keeps 5.
backpack["apples"] = 1A new key: apples is added with 1.
print(backpack)Shows {'pencils': 5, 'books': 2, 'apples': 1}

RUN IT

Read PyBot's menu.

Guess first. Then run real Python and check.

1

Guess the result

prices = {"juice": 2, "cake": 3} print(prices["cake"]) prices["juice"] = 4 print(prices)

What does the first print show?

menu.pyREAL PYTHON
OUTPUT
Ready. Press Run Python.
Python runs here thanks to Pyodide โ™ฅ

Pyodide 314.0.3 runs CPython in your browser with WebAssembly.

Open-source under the Mozilla Public License 2.0. License

Now change one thing: Add a new food with its price, like prices["soup"] = 5, and print the menu again.

YOUR TURN

Find it by key.

Try each tiny question. A wrong answer becomes something to review.

0Completed
9Not tried
0Review
01

Look it up

In a real dictionary you look up the word cat and find its meaning.

In a Python dictionary, the word you look up is called...

02

Whose age?

ages = {"Ana": 9, "Leo": 8} print(ages["Leo"])

What does print show?

03

Spot the dictionary

Which one is a dictionary?

04

A new cat

pets = {"cats": 1} pets["cats"] = 2 print(pets["cats"])

What does print show?

05

Add a color

colors = {"sky": "blue"} colors["grass"] = "green" print(colors)

What does print show?

06

No pizza here

menu = {"juice": 2} print(menu["pizza"])

What happens?

07

Is it on the menu?

menu = {"juice": 2} print("cake" in menu)

What does print show?

08

Fix PyBot's code

PyBot wants to know how many books are in the backpack, but Python stops. Make it show: 2

Goal output
2
OUTPUT

Your work is saved here.

Want a fresh start? Clear only this page.

!
BIG IDEA

A dictionary finds things by key.

Each pair is key: value. Use the key in [ ] to read a value, change it, or add a new one.