Module 04 · Lesson 01
Dictionaries & Hash Maps
Look values up by name instead of position with dictionaries: add, change and remove entries, read safely with get(), loop over keys, values and items, and count things.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Keys and values
- Look up safely
- Count with a dictionary
- Watch a backpack fill
Look things up by name
A dictionary pairs each key with a value, like a word with its meaning. You find a value by its key, not by its position.
Keys and values
Curly brackets, a colon in each pair:
ages = {"Ana": 14, "Bo": 12}.Look up
ages["Ana"]gives 14.ages.get("Cy", 0)gives 0 instead of an error when the key is missing.Change
ages["Cy"] = 11adds or replaces a pair.pop()anddeltake one out.Loop
for name, age in ages.items():visits every pair.
Lookups all around you
Whenever you find something by its name, a dictionary is a good fit.
- ContactsA name is the key and the phone number is the value.
- InventoriesEach item a player carries maps to how many they have.
- TranslationsAn English word maps to the same word in another language.
- Settings
{"volume": 7, "dark_mode": True}keeps every option under a clear name.
Storing under a key
This line adds or changes one pair. Tap each part to see its job.
Part 1 of 4
dictionary:An existing dictionary, for example stock = {"pears": 2}.
Look up and update
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Look up
Brackets need the key to exist. get() lets you choose a fallback.
Your turn: Add Peru and its capital, Lima, then look it up again.
capitals = {"France": "Paris", "Japan": "Tokyo", "Kenya": "Nairobi"}
print(capitals["Japan"])
print(capitals.get("Peru", "not saved yet"))Press Run to see what it prints.Watch a backpack fill up
Press Step to run one line at a time. Watch keys appear and values change in the names box.
Ready. Press Step to run the first line.
- inventory = {"sword": 1}
- inventory["potion"] = 3
- inventory["potion"] -= 1
- inventory["shield"] = inventory.get("shield", 0) + 1
- print(inventory)
- print(len(inventory), "kinds of item")
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.The same key twice: what prints?
d = {"a": 1, "a": 2}
print(d)0 of 6 answered
Common dictionary misconceptions
Each card is something beginners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
d = {"a": 1, "b": 2} d = {} d = dict(a=1, b=2)
d["a"] # KeyError if missing
d.get("z") d.get("z", 0)
d["c"] = 3 d["a"] += 1 del d["b"] d.pop("c")
"a" in d # checks keys
for k in d: for v in d.values(): for k, v in d.items():
counts[x] = counts.get(x, 0) + 1
groups.setdefault(key, []).append(item)Press Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
A small phone book
Store three contacts, add a new one, change a number, then look up a name that exists and one that does not without crashing.
phone = {"Ana": "0711 111", "Bo": "0722 222", "Cy": "0733 333"}
phone["Dee"] = "0744 444"
phone["Bo"] = "0799 999"
for name in ["Bo", "Eve"]:
print(name, phone.get(name, "not found"))
print(sorted(phone))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Reading a missing key with brackets
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
stock = {"apples": 5}
print(stock["pears"])Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Hospitality
A cafe order tally
At the end of a shift, a cafe till counts how many of each drink was sold and works out the takings from a price list.
Why Python fits
One dictionary is a fixed price list and the other is built by counting. Keys connect the two: each drink name looks up its price.
Pythonprices = {"tea": 2.0, "latte": 3.2, "juice": 2.5} orders = ["latte", "tea", "latte", "juice", "latte", "tea"] sold = {} for drink in orders: sold[drink] = sold.get(drink, 0) + 1 takings = 0 for drink, count in sold.items(): takings += count * prices[drink] print(f"{drink}: {count}") print(f"Takings: {takings:.2f}")OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Are dictionaries ordered?
How do I sort a dictionary by its values?
What is the difference between {} and set()?
Can two keys have the same value?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 8 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.