Computational
Thinking 7
Dictionaries: storing values against keys, reading and writing them, looping through keys, checking whether a key exists, and three worked examples: counting food purchases, finding shared birthdays and resolving pronouns.
Chapters
- 01What Is a Dictionary?Dictionaries
- 02Dictionary Basics: Create, Read, WriteDictionaries
- 03Looping Through a DictionaryDictionaries
- 04Checking If a Key ExistsDictionaries
- 05Counting Food PurchasesWorked example
- 06The Birthday ParadoxWorked example
- 07Resolving PronounsWorked example
- 08Week 7 Summary SheetAll topics
What Is a Dictionary?
Values stored against keys, reached in one step instead of by walking a list.
1.1Lists: one item after another
A list stores values one after another. If you want the 5th item, the only way to get there is to walk past the first four; there is no shortcut. That is fine for going through everything, but slow if you just want one specific thing.
1.2Dictionaries: a value against a key
A dictionary works differently. Instead of a position, every value is stored against a key: something meaningful you already know, like a name or an ID. Hand the dictionary the key, and it hands back the value immediately. It does not matter how big the dictionary is or which key you ask for: the lookup takes the same amount of time either way. This is called random access.
- Chemistry marks (value) stored against each student's name (key).
- A train's source station (value) stored against its train number (key).
1.3Reading a value
To read a value, put the key in square brackets after the dictionary's name:
m = chemMarks["Rahul"]
s = sourceStation["10215"]Give the dictionary a key, get the matching value back, with no searching involved.
| List | Dictionary | |
|---|---|---|
| Values are reached by | position (1st, 2nd, ...) | key (a name, an ID) |
| Getting one value | walk past the earlier items | one step: d[k] |
| Written as | [92, 73, 89] | {"Rahul":92, ...} |
| Good for | going through everything in order | finding one specific value fast |
"10215": a train number written in quotes is a label, not a quantity.1.4Exam tips and common mistakes
- When a question says "look up the value for this name/ID", think dictionary.
- Read
d[k]as "the value stored against key k".
- Thinking a dictionary has a first or fifth item: it has keys, not positions.
- Confusing the key (what you look up by) with the value (what you get back).
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
In m = chemMarks["Rahul"], what is "Rahul"?
What goes in the square brackets?
- The square brackets hold the key;
mreceives the value. - Answer: option 1.
Multiple Choice Question (MCQ): choose the one correct option.
Which statement describes random access in a dictionary?
Does the size matter?
- A lookup by key takes the same time whatever the size and whichever key is asked for.
- Answer: option 3.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
d[5] in every dictionaryCompare positions with keys.
- 1, 2 and 4 are true. A dictionary has no positions (statement 3 is false).
- Answer: options 1, 2 and 4.
Walk past earlier items
Name or ID as key
Size does not matter
chemMarks["Rahul"]
Dictionary Basics: Create, Read, Write
Curly braces, d = {}, reading with d[k], and writing that replaces or creates.
2.1Key : value pairs
At its core, a dictionary is just a set of key : value pairs, written inside curly braces:
{"Rahul":92, "Clarence":73, "Ritika":89}2.2The four basic operations
d = {}You always start with an empty dictionary before adding anything to it.
s = sourceStation["10215"]Square brackets around the key fetch the matching value.
chemMarks["Rahul"] = 92If the key already exists, this replaces its value. If it does not, it creates a new key–value pair on the spot.
d = {} first.2.3Filling a dictionary from a table
Read every row of a table and file each student's Chemistry mark into a dictionary, keyed by name:
chemMarks = {}
while (Table 1 has more rows) {
Read the first row X in Table 1
name = X.Name
marks = X.ChemistryMarks
chemMarks[name] = marks
Move X to Table 2
}With rows Rahul 92, Clarence 73 and Ritika 89 the dictionary grows {} → {"Rahul":92} → ... → {"Rahul":92, "Clarence":73, "Ritika":89}.
chemMarks["Rahul"] = 65 replaces 92: one of the two marks is lost without any warning. Keying by a unique field such as X.SeqNo avoids this.d[k] when k is not a key has no value to give back. That is why Chapter 4 checks with isKey before reading.2.4Exam tips and common mistakes
- Trace a dictionary as a two-column table: key, value.
- For every write, ask "does this key exist already?": replace or create.
- Forgetting
d = {}before the loop. - Expecting a write to an existing key to add a second pair: it replaces the value.
- Using square brackets
[]for an empty dictionary: that is an empty list.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
After d = {}, d["a"] = 1, d["b"] = 2, d["a"] = 5, what is d["a"]?
A write to an existing key replaces the value.
- The last write to "a" stores 5.
- Answer: 5
Numerical Answer Type (NAT).
After the same four statements, how many keys does d have?
Replacing does not add a key.
- The keys are "a" and "b".
- Answer: 2
Multiple Choice Question (MCQ): choose the one correct option.
Which statement creates an empty dictionary?
d = []d = {}d = 0d = ""Curly braces.
{}is an empty dictionary;[]is an empty list.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
chemMarks is built from rows Rahul 92, Ritika 89, Rahul 65 (keyed by name). What is chemMarks["Rahul"]?
The later write replaces the earlier one.
- The third row overwrites 92 with 65.
- Answer: option 2.
Always first
Key must exist
Replace or create
Unique keys matter
Looping Through a Dictionary
keys(d) gives a list of keys; loop over it and read d[k].
3.1Loop over the keys
A dictionary does not have positions, so you cannot loop through it the way you loop through a list. Instead, you first pull out the list of its keys, then loop through that.
Returns a plain list containing every key in dictionary d. Once you have that list, you loop through it like any other list, using each key to reach its value with d[k].
foreach k in keys(d) {
Do something with d[k]
}3.2Example: the average Chemistry mark
Add up every value in the dictionary and divide by how many there are:
total = 0
count = 0
foreach k in keys(chemMarks) {
total = total + chemMarks[k]
count = count + 1
}
chemAvg = total / count| k | chemMarks[k] | total | count |
|---|---|---|---|
| "Rahul" | 92 | 92 | 1 |
| "Clarence" | 73 | 165 | 2 |
| "Ritika" | 89 | 254 | 3 |
chemAvg = 254 / 3 ≈ 84.67. It is the same idea as averaging a list: the only difference is that you reach each value through its key instead of its position.
3.3Going deeper
- The order of keys (extra). The lecture does not promise any particular order for
keys(d). Sums, counts and maxima do not depend on it, so write code that does not either. - Counting without a counter (extra).
length(keys(chemMarks))gives the number of keys directly. - An empty dictionary (extra). With no keys,
countstays 0 andtotal / countdivides by zero; check for this first.
3.4Exam tips and common mistakes
- Write the keys list first, then trace one row per key.
- Writing
foreach k in d: loop overkeys(d). - Adding the keys instead of
d[k].
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
For {"Rahul":92, "Clarence":73, "Ritika":89}, what is chemAvg? (Two decimal places.)
Sum of values over the number of keys.
- (
92 + 73 + 89) /3=254/3. - Answer: 84.67
Multiple Choice Question (MCQ): choose the one correct option.
What does keys(chemMarks) return?
Only the keys.
- A plain list of the keys; the values are read with
chemMarks[k]. - Answer: option 3.
Numerical Answer Type (NAT).
What is s after this code runs?
d = {"x":4, "y":7, "z":9}
s = 0
foreach k in keys(d) {
s = s + d[k]
}Add the values.
4 + 7 + 9 = 20.- Answer: 20
No positions in d
254 / 3 ≈ 84.67
Checking If a Key Exists
isKey(d, k) and the accumulator pattern: add if the key exists, create it if not.
4.1Running totals need a check
Dictionaries are often used to keep a running total: runs scored by a player, items bought by a customer, and so on. Say you are adding up runs for Virat Kohli match by match. Every time you see his name you want to add to his total, except the very first time, when there is no total yet to add to. So before updating a key you need to know: does this key already exist, or am I creating it for the first time?
Returns True if k is already a key in d, and False otherwise.
4.2The accumulator pattern
Update if the key exists, create it if it does not:
if (isKey(runs, "Kohli")) {
runs["Kohli"] = runs["Kohli"] + score
}
else {
runs["Kohli"] = score
}| Match score | isKey(runs, "Kohli") | Branch | runs["Kohli"] after |
|---|---|---|---|
| 45 | False | else: start | 45 |
| 12 | True | add | 57 |
| 78 | True | add | 135 |
(Scores 45, 12, 78 are illustrative.) Without the check, the first runs["Kohli"] + score would read a key that does not exist yet.
4.3How isKey works underneath
The simplest way to write isKey is to walk through every key checking for a match:
Procedure isKey(D, k)
found = False
foreach key in keys(D) {
if (key == k) {
found = True
exitloop
}
}
return(found)
End isKeyOn chemMarks (keys "Rahul", "Clarence", "Ritika"), isKey(chemMarks, "Ritika") makes 3 comparisons before it finds the key; isKey(chemMarks, "Asha") makes 3 and returns False. A missing key always costs one comparison per key.
This version takes longer the bigger the dictionary gets, since it checks key after key. Real dictionaries do not work this way: they can jump straight to a key, so isKey runs in constant time no matter the size. That is the version used from here on.
4.4Going deeper
- exitloop again (extra). The loop stops at the first match, the same trick as in Week 6's grade checks.
- Any running total (extra). Replace
scorewith 1 and the pattern counts occurrences instead of adding amounts.
4.5Exam tips and common mistakes
- Trace with columns: the item, isKey, the branch, the value after.
- Updating without checking, which reads a missing key the first time.
- Swapping the branches: setting
d[k] = vwhen the key exists throws away the total.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What is count["a"] after this code?
count = {}
foreach w in ["a", "b", "a", "c", "a"] {
if (isKey(count, w)) {
count[w] = count[w] + 1
}
else {
count[w] = 1
}
}The pattern with v = 1.
- "a" appears three times: 1, then 2, then 3.
- Answer: 3
Numerical Answer Type (NAT).
For the same code, how many keys does count have at the end?
One key per distinct word.
- "a", "b" and "c".
- Answer: 3
Numerical Answer Type (NAT).
A dictionary has 5 keys and k is not one of them. How many times does the simple isKey compare key == k?
No match, no exitloop.
- Every key is compared once.
- Answer: 5
Multiple Choice Question (MCQ): choose the one correct option.
In the accumulator pattern, when does d[k] = v (the else branch) run?
isKey is False.
- Only the first time k is seen; afterwards k is a key.
- Answer: option 2.
New: create
exitloop on a match
Used from now on
Counting Food Purchases
The accumulator pattern on customer orders, then a maximum over the keys.
5.1The problem
Given a table of customer orders, find who bought the most food items. This is the accumulator pattern applied directly. Keep a dictionary keyed by customer name. Every time a customer's order contains a "Food" item, either bump their count by one, or start it at one if this is the first time we have seen them.
foodD = {}
while (Table 1 has more rows) {
Read the first row X in Table 1
customer = X.CustomerName
items = X.Items
foreach row in items {
if (row.Category == "Food") {
if (isKey(foodD, customer)) {
foodD[customer] = foodD[customer] + 1
}
else {
foodD[customer] = 1
}
}
}
Move X to Table 2
}X.Itemsis the list of items in one order; each item has aCategory.- The inner
foreachgoes through those items, so one order can add several to the count. - Once every row has been processed,
foodDholds each customer's total food item count.
5.2A run on five orders (illustrative)
| Order | Customer | Items | Food items | foodD after |
|---|---|---|---|---|
| 1 | Ahmed | Food, Stationery, Food | 2 | {"Ahmed":2} |
| 2 | Bhuvan | Toiletries | 0 | {"Ahmed":2} |
| 3 | Ahmed | Food | 1 | {"Ahmed":3} |
| 4 | Charu | Food, Food | 2 | {"Ahmed":3, "Charu":2} |
| 5 | Bhuvan | Food | 1 | {"Ahmed":3, "Charu":2, "Bhuvan":1} |
if never runs and Bhuvan is not a key yet. He becomes a key only with order 5.5.3Finding the top customer
The lecture says to loop through keys(foodD) to find whoever has the highest value. Written out (a max loop from Week 2, over keys):
maxCount = 0
topCustomer = ""
foreach c in keys(foodD) {
if (foodD[c] > maxCount) {
maxCount = foodD[c]
topCustomer = c
}
}On the run above: topCustomer = "Ahmed", maxCount = 3.
5.4Going deeper
- Customers with no food (extra). They never become keys, so a question like "how many customers bought no food" cannot be answered from
foodDalone. - Ties (extra). With a strict
>the first customer reached with the top count is kept; since the order ofkeysis not fixed, report all customers withmaxCountif ties matter. - Names as keys (extra). Two different customers with the same name would be counted together.
5.5Exam tips and common mistakes
- Count Food items per order first, then add to the customer's running total.
- Adding 1 per order instead of per Food item.
- Assuming every customer is a key.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
In the five-order run, what is foodD["Ahmed"] at the end?
Count his Food items over both orders.
- 2 in order 1, 1 in order 3.
- Answer: 3
Numerical Answer Type (NAT).
How many keys does foodD have after the first two orders?
Bhuvan bought no food yet.
- Only "Ahmed".
- Answer: 1
Multiple Choice Question (MCQ): choose the one correct option.
Which statement finds the customer with the most food items once foodD is built?
foodD[1]keys(foodD) keeping the largest foodD[c]first(keys(foodD))isKey(foodD, "Food")Loop over the keys.
- A max loop over
keys(foodD)comparingfoodD[c]. - Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
Who becomes a key, and when?
- 1 and 3 are true. One order can add more than 1 (statement 2 is false); the count is per customer, not per order (statement 4 is false).
- Answer: options 1 and 3.
Food item: +1 or start at 1
Ahmed: 3
The Birthday Paradox
Grouping students by date of birth with a dictionary of dictionaries, in one pass.
6.1The problem
Out of a class of students, find any birthdays that are shared by more than one person. Start simple: a dictionary keyed by date of birth. The first time a date is seen, record it. If it turns up again, that date is a duplicate. A second dictionary, duplicates, keeps track of which dates were shared.
To also know which students share a birthday, go one step further: instead of storing True against a date, store a dictionary of student IDs. That inner dictionary grows every time another student with the same birthday shows up.
birthdays = {}
duplicates = {}
while (Table 1 has more rows) {
Read the first row X in Table 1
dob = X.DoB
seqno = X.SeqNo
if (isKey(birthdays, dob)) {
duplicates[dob] = True
birthdays[dob][seqno] = True
}
else {
birthdays[dob] = {}
birthdays[dob][seqno] = True
}
Move X to Table 2
}birthdays[dob] is itself a dictionary: its keys are the IDs of every student born on that date. Nesting dictionaries like this is completely normal; a value can be anything, including another dictionary. birthdays[dob][seqno] = True writes into the inner one.
birthdays[dob][seqno] needs birthdays[dob] to exist, the "dictionary has to exist first" rule of Chapter 2, one level down.6.2A run on eight students (illustrative)
| SeqNo | DoB | isKey(birthdays, dob) | What happens |
|---|---|---|---|
| 0 | 12 Mar | False | new inner {0} |
| 1 | 5 Jul | False | new inner {1} |
| 2 | 12 Mar | True | duplicate; add 2 |
| 3 | 21 Oct | False | new inner {3} |
| 4 | 5 Jul | True | duplicate; add 4 |
| 5 | 30 Jan | False | new inner {5} |
| 6 | 12 Mar | True | duplicate; add 6 |
| 7 | 9 Sep | False | new inner {7} |
To list the students who share each date (extra; the slide stops at building the dictionaries):
foreach d in keys(duplicates) {
sharers = keys(birthdays[d])
// sharers is the list of SeqNos born on date d
}This gives "12 Mar": 0, 2, 6 and "5 Jul": 1, 4.
6.3Why it is called a paradox (extra)
Most people guess that you need well over a hundred people before two are likely to share a birthday. In fact the chance passes 50% at just 23 people (ignoring 29 February and assuming every day is equally likely):
| People | Chance that at least two share a birthday |
|---|---|
| 23 | 50.7% |
| 30 | 70.6% |
| 40 | 89.1% |
| 50 | 97.0% |
| 70 | 99.9% |
The reason is the number of pairs: 23 people make 23 × 22 / 2 = 253 pairs, and each pair is a chance of a match. In a class of 30, a shared birthday is more likely than not. (Computed as one minus the chance that all birthdays differ.)
6.4One pass instead of every pair (extra)
Week 4 compared every pair of students, N × (N − 1) / 2 comparisons, and used binning by month to cut that down. The dictionary does the grouping in one pass: each student costs one isKey lookup, which is constant time. For 8 students that is 8 lookups instead of 28 comparisons; for 30 students, 30 instead of 435. In effect the dictionary is a bin per date.
6.5Going deeper
- Day and month (extra). A birthday is a day and a month. If
DoBalso held the year, students born on the same day in different years would not match; the key should then be built from the day and month only. - Setting True twice (extra). When a date turns up a third time,
duplicates[dob] = Trueruns again; writing the same value again changes nothing.
6.6Exam tips and common mistakes
- Trace with a table: date, isKey, and the inner dictionary after the row.
- Writing
birthdays[dob][seqno]beforebirthdays[dob] = {}. - Counting a date as a duplicate the first time it is seen.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
In the eight-student run, how many keys does duplicates have?
Dates seen more than once.
- "12 Mar" and "5 Jul".
- Answer: 2
Numerical Answer Type (NAT).
How many keys does the inner dictionary birthdays["12 Mar"] have?
Students born on 12 Mar.
- SeqNos 0, 2 and 6.
- Answer: 3
Numerical Answer Type (NAT).
How many comparisons would comparing every pair of the eight students need?
½ × N × (N − 1).
8 × 7 / 2 = 28.- Answer: 28
Multiple Choice Question (MCQ): choose the one correct option.
Why does the else branch run birthdays[dob] = {} before birthdays[dob][seqno] = True?
One level down, the same rule.
- The inner dictionary must exist before anything is written into it.
- Answer: option 3.
Value: dict of SeqNos
Shared dates only
30 people: 70.6%
not N(N−1)/2
Resolving Pronouns
A dictionary of lists by part of speech, and the nearest noun before each pronoun.
7.1The problem
In a sentence, match every pronoun to the noun it refers to: specifically, the nearest noun that comes before it. Each word in the source table has a serial number marking its position in the sentence.
7.2Step 1: two lists in one dictionary
First, sort every word into one of two buckets by part of speech, keeping the serial numbers in the order they were read:
partOfSpeech = {}
partOfSpeech["Noun"] = []
partOfSpeech["Pronoun"] = []
while (Table 1 has more rows) {
Read the first row X in Table 1
if (X.PartOfSpeech == "Noun") {
partOfSpeech["Noun"] = partOfSpeech["Noun"] ++ [X.SerialNo]
}
if (X.PartOfSpeech == "Pronoun") {
partOfSpeech["Pronoun"] = partOfSpeech["Pronoun"] ++ [X.SerialNo]
}
Move X to Table 2
}Here the values of the dictionary are lists. Both lists come out sorted in ascending order of serial number, since the table is read in order.
7.3Step 2: the nearest noun before each pronoun
For every pronoun, walk through the noun list and keep the last noun whose serial number is still smaller than the pronoun's. The moment a noun's serial number catches up to or passes the pronoun's, stop: whatever was last saved is the nearest one before it.
matchD = {}
foreach p in partOfSpeech["Pronoun"] {
matched = -1
foreach n in partOfSpeech["Noun"] {
if (n < p) {
matched = n
}
else {
exitloop
}
}
matchD[p] = matched
}Result: matchD[p] holds the serial number of the noun that pronoun p refers to.
7.4Two sentences (illustrative)
"The teacher praised Asha because she worked hard." Nouns: [2, 4] (teacher, Asha). Pronouns: [6] (she).
| p | n | n < p? | matched |
|---|---|---|---|
| 6 | 2 | yes | 2 |
| 6 | 4 | yes | 4 |
| (no more nouns) | matchD[6] = 4 |
"Rahul gave Ritika a book and she thanked him." Nouns: [1, 3, 5], pronouns: [7, 9]. The rule gives matchD[7] = 5 and matchD[9] = 5: both "she" and "him" are matched to "book".
7.5Going deeper
- No noun before (extra). In "She met Ravi", the first noun (3) is already after the pronoun (1), so the loop exits at once and
matchD[1] = -1: -1 means "no noun found". - Why exitloop is safe. The noun list is ascending, so once one noun is not before p, none of the later ones are.
- Comparisons (extra). In the second sentence, pronoun 7 checks nouns 1, 3, 5 and pronoun 9 checks 1, 3, 5 again: 6 comparisons. Because the pronouns are also in order, the inner loop could carry on from where the previous pronoun stopped.
- n == p cannot happen. A word is either a noun or a pronoun, so serial numbers in the two lists never coincide.
7.6Exam tips and common mistakes
- List the noun and pronoun serial numbers first.
- For each pronoun, the answer is the largest noun number smaller than it.
- Taking the nearest noun after the pronoun.
- Forgetting
matched = -1for each pronoun.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
Nouns are at [2, 4] and the pronoun is at 6. What is matchD[6]?
The largest noun number below 6.
- Noun 4.
- Answer: 4
Numerical Answer Type (NAT).
In "She met Ravi" (She = 1, Ravi = 3, a noun), what is matchD[1]?
No noun comes before 1.
- The first noun is 3, not below 1, so the loop exits with matched = -1.
- Answer: -1
Numerical Answer Type (NAT).
Nouns [1, 3, 5], pronouns [7, 9]. How many times is n < p evaluated?
No exitloop happens.
- 3 for pronoun 7, 3 for pronoun 9.
- Answer: 6
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
Think about order and the heuristic.
- 1, 2 and 3 are true. The rule can pick the wrong noun (statement 4 is false).
- Answer: options 1, 2 and 3.
partOfSpeech["Pronoun"]
Lists, ascending
exitloop otherwise
-1 if none
she → book is possible
Week 7 Summary Sheet
One page to revise all of Week 7: the dictionary operations, the accumulator pattern and the three worked examples.
Cheat sheet
| Operation | Meaning |
|---|---|
d = {} | Create an empty dictionary |
d[k] = v | Add a new key, or overwrite the value of an existing one |
v = d[k] | Read the value stored against key k |
keys(d) | Get a list of every key in d |
foreach k in keys(d) { ... } | Loop through every key–value pair |
isKey(d, k) | True if k already exists as a key in d |
Patterns and how to use them
if (isKey(d, k)) {
d[k] = d[k] + v
}
else {
d[k] = v
}Use whenCounting or totalling per key: runs per player, items per customer, words per text.
- Check
isKey(d, k). - If it exists, add v to
d[k]. - Otherwise start it:
d[k] = v(v = 1 to count).
d = {}
while (Table 1 has more rows) {
Read the first row X in Table 1
d[X.Name] = X.ChemistryMarks
Move X to Table 2
}Use whenYou will later need the value for a given key quickly.
- Start with
d = {}. - Write
d[key] = valuefor each row. - Use a unique field as the key, or values are overwritten.
foreach k in keys(d) {
total = total + d[k]
count = count + 1
}Use whenYou need every value: totals, averages, a maximum.
- Get the list with
keys(d). - Read each value with
d[k]. - Do not rely on the order of the keys.
if (isKey(groups, g)) {
groups[g][id] = True
}
else {
groups[g] = {}
groups[g][id] = True
}Use whenYou want to know which items share a value (same birthday, same city).
- Create the inner dictionary the first time g is seen.
- Add the id into
groups[g]. keys(groups[g])lists the members.
d["Noun"] = []
d["Pronoun"] = []
d["Noun"] = d["Noun"] ++ [X.SerialNo]Use whenItems fall into a few named buckets and order matters inside each.
- Create each bucket as an empty list.
- Append with
++. - Read a bucket like any list.
maxCount = 0
topCustomer = ""
foreach c in keys(foodD) {
if (foodD[c] > maxCount) {
maxCount = foodD[c]
topCustomer = c
}
}Use whenThe answer is the key with the largest value.
- Start the maximum at 0.
- Loop over
keys(d), keeping the key with the largestd[k]. - Decide what to do with ties.
Which tool when?
| Situation | Tool |
|---|---|
| Find the value for a name or ID | d[k] |
| Keep a total per key | The accumulator pattern with isKey |
| Go through all values | foreach k in keys(d) |
| Group items by a shared value | A dictionary of dictionaries (or of lists) |
| Find items that share a value | One pass with a dictionary, not every pair |
| Collect items per category, in order | A dictionary whose values are lists |
Anywhere you would otherwise search a list to find "the row that matches this ID", a dictionary gets you there in one step instead. That is the entire idea: trade a bit of structure up front for constant-time lookups later.
Common mistakes
- The dictionary must exist before anything is written into it, at every level of nesting.
- Check
isKeybefore readingd[k]in a running total.
- Writing to an existing key replaces its value; it never creates a second pair.
- Two students with the same name overwrite each other; key by SeqNo.
- Loop over
keys(d), and do not depend on its order.
- The nearest noun is a rule of thumb; it can match "she" to "book".