A dictionary maps unique, hashable keys to values, letting a program retrieve information by meaning rather than position.
Build lookups and tallies, update entries and distinguish a missing key from a stored zero or None.
A menu connects a dish name to a price. A scorecard connects a player to a running total. Both use keys, but they update values differently. Begin with lookup and missing-data policies, then build counting and grouping from explicit read, combine and write steps.
![A canteen menu drawn as key boxes pointing to value boxes: "tea" to 15, "samosa" to 20, "dosa" to 60. On the right, menu["dosa"] gives 60, menu["pizza"] raises KeyError, and menu.get("pizza", 0) gives the default 0. A note says assigning menu["tea"] = 12 replaces 15, because each key appears once](/api/assets/python/assets/fb2a9698d7efb62d.png)
Price a canteen order
The canteen keeps its prices in a dict. Write it as {key: value, ...} and read
a price with square brackets:
To bill a table, look up every dish they ordered and add the prices. Then someone orders something the canteen doesn't sell:
KeyErrorOne unknown dish crashes the whole bill. Make missing dishes count as 0.
Use [] when a missing key is a bug you want to hear about. Use .get() when a
missing key is normal. menu.get("pav bhaji") with no default gives None.
in only ever looks at the keys:
menu = {"tea": 15, "samosa": 20, "dosa": 60}
print(60 in menu, "dosa" in menu)Taking dishes off the board works by key too:
Preparing this topic’s interactive investigation…
Missing, zero and None are different states
The default is used only when the key is absent. A stored None stays None,
and a stored zero stays zero. prices.get(dish) or 10 would replace both
with 10, destroying this distinction. Membership asks whether the key
exists; indexing reads its value and raises if it does not.
The bill exercise deliberately assigns unknown dishes a zero contribution. That is a local exercise rule: a real order system might reject an unknown dish rather than silently charge nothing. Make the choice where missing data enters, so callers do not accidentally treat “unknown” as “free.”
Score a cricket innings
Ball by ball, the scorer notes who hit how many runs. A dict turns that stream into a scorecard: batter → total runs. The obvious first try:
KeyErrorThe very first ball crashes the scorer. Start each batter at 0.
runs[batter] = runs.get(batter, 0) + r accumulates runs; adding 1
instead would count scoring events, which answers a different question. Now loop the finished dict.
A plain for gives the keys; .values() gives the values; .items() gives
both as pairs:
max(runs, key=runs.get) walks the keys but compares them by their values, so
it returns the name of the top scorer. A dict also remembers the order its
keys were added, so the scorecard prints in batting order.
Tallies like this are so common that Python ships two helpers in
collections: Counter counts things for you, and defaultdict fills in a
starting value for a missing key. A later section covers both properly:
Read, combine, write
For a tally, every event reads the old total (or zero), combines it with the
new amount, and writes back under the same key. For grouping, the value is
a list rather than a number. setdefault(key, []) returns the existing list
or installs the supplied empty list when the key is absent; append then
changes that bucket. .get(key, []) alone does not install a bucket.
This is why grouping is more than shortening a loop. Its invariant is:
after each word, every processed word belongs to exactly its selected bucket,
in arrival order. The first-letter exercise assumes nonempty words; an empty
string needs a separate policy before indexing word[0].
Extend that idea to events [category, amount]: compute both event count and
amount total per category. Two events of amounts 3 and 7 should yield
count 2 and amount 10, making a mistaken + 1 easy to detect.
Fill in a booking form
A travel app starts every booking from the same template. The values can be any type, so one booking holds text, numbers and a nested dict:
a | b builds a new dict: everything in a, then b on top (the right side
wins on a clash). The mistake comes when someone builds a booking with a plain
=:
template = {"class": "SL", "meal": False}
booking = template
booking["class"] = "3A"
print(template["class"])Step through it and watch the second name point at the same dict, then a real copy go its own way:
.copy(), dict(template), {**template} and template | {} all make a new
outer dict. They are shallow: a nested list or dict inside is still shared.
For this nested list/dictionary structure, copy.deepcopy(template) also
copies the nested mutable containers. Copying arbitrary application objects
needs an explicit ownership policy; not every resource can be duplicated.
Traps and one-liners
Trap: keys must be hashable.
{["Pune", "Nagpur"]: 540}raisesTypeError: unhashable type: 'list'. Use a tuple:{("Pune", "Nagpur"): 540}.
Which collection? An ordered row you'll change: list. A fixed record that never changes: tuple. Unique items, fast "is it in here?": set. Look something up by name: dict.
Quick practice
prices = {"tea": 10, "samosa": 20, "tea": 12}
print(prices["tea"], len(prices))menu = {"tea": 15, "dosa": 60}
print(menu.get("vada"), menu.get("vada", 0))RuntimeErrorRemove the sold-out items without crashing.
🎯 Your turn
Write order_total(order, menu). It adds up the price of every dish in the
order, and a dish that isn't on the menu counts as 0.
order_total(["soup", "steak"], {"soup": 10, "steak": 20})→30order_total(["soup", "cake"], {"soup": 10})→10
Hint: start total = 0, loop the order, add menu.get(dish, 0) each time,
and return total.
Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from totalling values to merging menus.
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write total_values(d) returning the sum of all the dict's values (0 for an empty dict).
Write longest_key(d) returning the key with the most characters. (Assume one clear winner.)
Write group_by_first(words) returning a dict mapping each first letter to the list of words starting with it, order preserved.
Write word_count(text) returning a dict of word -> count (split on whitespace).
Write merge_menus(base, *overrides) merging any number of override dicts onto base, left to right (later values win). Don't mutate the inputs.