A real dictionary
You look up a word and find what it means. Word, then meaning.
09SUPERPOWERS ยท DICTIONARIES
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
You look for the label, and next to it is the value.
You look up a word and find what it means. Word, then meaning.
Next to each name is a phone number. Name, then number.
Next to each food is its price. Food, then price.
LOOK FIRST
A dictionary goes inside { }. Each pair is key: value. The label is called a key.
backpack["pencils"] gives back the value with that key.
backpack["pencils"] = 5 changes the value. A new key adds a new pair.
STEP BY STEP
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 3backpack["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
Guess first. Then run real Python and check.
prices = {"juice": 2, "cake": 3}
print(prices["cake"])
prices["juice"] = 4
print(prices)What does the first print show?
PyBot's hint
Ready. Press Run Python.
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
Try each tiny question. A wrong answer becomes something to review.
In a Python dictionary, the word you look up is called...
ages = {"Ana": 9, "Leo": 8}
print(ages["Leo"])What does print show?
Which one is a dictionary?
pets = {"cats": 1}
pets["cats"] = 2
print(pets["cats"])What does print show?
colors = {"sky": "blue"}
colors["grass"] = "green"
print(colors)What does print show?
menu = {"juice": 2}
print(menu["pizza"])What happens?
menu = {"juice": 2}
print("cake" in menu)What does print show?
PyBot wants to know how many books are in the backpack, but Python stops. Make it show: 2
2OUTPUT
Want a fresh start? Clear only this page.
Each pair is key: value. Use the key in [ ] to read a value, change it, or add a new one.