python · level 2 · unit 1 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A finds a value by its name, not its place.
A list finds things by position: item 0, item 1, item 2. A dictionary finds things by name, like a café menu where you look up tea and read its price. Each name is a , and each key points to one value.
Write a dictionary in curly brackets. Each pair is a key, a colon, then its value, with commas between the pairs. To look a value up, put its key in square brackets: prices["tea"].
Keys are unique, so the menu cannot list tea twice. Ask for a key that is not there, like prices["cake"], and Python stops with a .
prices = {"tea": 1.5, "coffee": 2.2, "toast": 1.8}
print(prices["coffee"])
print(prices) Printing a whole dictionary shows every pair, in the order you added them.
guess first
The café has sold out of cake. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
stock = {"scones": 6, "muffins": 4}
print(stock["muffins"])
print(stock["cake"])
your turn
Your turn. Build a pet age lookup.
Fill in three pets and their ages. Then put one of those names in the pet box and run it to look that pet up.
fix it
The phone book cannot find Sam. Can you fix it?
- Read the last line of the error. Which key could Python not find?
- Keys are case-sensitive, like every name in Python. Compare the key on line 2 with the one on line 1.
- Change "sam" to "Sam" on line 2, then run.
nailed it
you built your first lookup table. :D
- A dictionary stores values under keys, inside curly brackets.
- Look a value up with its key in square brackets.
- A missing key stops the program with a KeyError.
new words in your collection
- dictionary
- key
- KeyError
This lesson isn’t saved. A free account remembers every lesson you finish.