Skip to the workspace
Pebellslearn by building
Fundamentals  ›  Lesson

Dictionaries

Dictionaries 22 minA dictionary maps unique, hashable keys to values, letting a program retrieve information by meaning rather than position.

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

Price a canteen order

The canteen keeps its prices in a dict. Write it as {key: value, ...} and read a price with square brackets:

python

To bill a table, look up every dish they ordered and add the prices. Then someone orders something the canteen doesn't sell:

broken — fix itKeyError

One 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:

What does this print?
menu = {"tea": 15, "samosa": 20, "dosa": 60}
print(60 in menu, "dosa" in menu)

Taking dishes off the board works by key too:

python

Preparing this topic’s interactive investigation…

Missing, zero and None are different states

python

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:

broken — fix itKeyError

The 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:

python

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:

python

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.

python

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:

python

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 =:

What does this print?
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:

step through it
1template = {"class": "SL", "meal": False}
2booking = template
3booking["class"] = "3A"
4fresh = template.copy()
5fresh["class"] = "2A"
6print(template, fresh)

.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

python

Trap: keys must be hashable. {["Pune", "Nagpur"]: 540} raises TypeError: 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

What does this print?
prices = {"tea": 10, "samosa": 20, "tea": 12}
print(prices["tea"], len(prices))
What does this print?
menu = {"tea": 15, "dosa": 60}
print(menu.get("vada"), menu.get("vada", 0))
broken — fix itRuntimeError

Remove 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}) → 30
  • order_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.

Your task
Build order_total(order, menu). Given a list of ordered dishes and a menu dict that maps dish → price, return the total price. Unknown dishes count as 0. Example: order_total(["soup", "steak"], {"soup": 10, "steak": 20}) → 30.

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upTotal the values

Write total_values(d) returning the sum of all the dict's values (0 for an empty dict).

dict-valuessum
DrillLongest key

Write longest_key(d) returning the key with the most characters. (Assume one clear winner.)

max-key
BuildGroup by first letter

Write group_by_first(words) returning a dict mapping each first letter to the list of words starting with it, order preserved.

setdefaultloop
BossWord frequency

Write word_count(text) returning a dict of word -> count (split on whitespace).

dict.getsplitloop
CapstoneMerge menus

Write merge_menus(base, *overrides) merging any number of override dicts onto base, left to right (later values win). Don't mutate the inputs.

*argsdict-merge
Project context and further resources
You're building a piece ofBill Splitter & Tip Calculator
This piece — order_total(): Maps dish → price and totals an order.
Scenario The kitchen keeps a price menu (dish → price). To bill the table, the app looks up every dish the table ordered and adds the prices.
order_total.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
order_total(order, menu) → floatTotal price of an order, looking each dish up in the menu.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.