Weeks
Computational ThinkingWeek 7 · Dictionaries
Week 7 Notes

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.

8 chapters26 worked examples~25 min read
DictionarieskeysisKeyAccumulatorNested dictionaries

Chapters

  1. 01What Is a Dictionary?Dictionaries
  2. 02Dictionary Basics: Create, Read, WriteDictionaries
  3. 03Looping Through a DictionaryDictionaries
  4. 04Checking If a Key ExistsDictionaries
  5. 05Counting Food PurchasesWorked example
  6. 06The Birthday ParadoxWorked example
  7. 07Resolving PronounsWorked example
  8. 08Week 7 Summary SheetAll topics
01
Dictionaries

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.

List: walk past items 1 to 4 to reach the 5th606774818895Dictionary: the key jumps straight to its value"Ritika""Ritika"89same time for any key
Figure 1. A list is walked position by position; a dictionary goes straight to the key
Real examples
  • 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:

read.pseudo
m = chemMarks["Rahul"]
s = sourceStation["10215"]

Give the dictionary a key, get the matching value back, with no searching involved.

ListDictionary
Values are reached byposition (1st, 2nd, ...)key (a name, an ID)
Getting one valuewalk past the earlier itemsone step: d[k]
Written as[92, 73, 89]{"Rahul":92, ...}
Good forgoing through everything in orderfinding one specific value fast
Comparison (extra). This table is a reading aid, not a slide. Note that the key is often a string like "10215": a train number written in quotes is a label, not a quantity.

1.4Exam tips and common mistakes

Exam tips
  • When a question says "look up the value for this name/ID", think dictionary.
  • Read d[k] as "the value stored against key k".
Common mistakes
  • 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)

Q1Key or value?

Multiple Choice Question (MCQ): choose the one correct option.

In m = chemMarks["Rahul"], what is "Rahul"?

1
The key
2
The value
3
A position
4
The dictionary
Solution
Idea

What goes in the square brackets?

  • The square brackets hold the key; m receives the value.
  • Answer: option 1.
Q2Random access

Multiple Choice Question (MCQ): choose the one correct option.

Which statement describes random access in a dictionary?

1
Keys are chosen at random
2
Values come back in a random order
3
Any key's value is reached in the same time, whatever the size
4
You must walk through the keys in order
Solution
Idea

Does the size matter?

  • A lookup by key takes the same time whatever the size and whichever key is asked for.
  • Answer: option 3.
Q3Lists and dictionaries

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements.

1
To reach the 5th item of a list you pass the first four
2
A dictionary stores values against keys
3
A dictionary's 5th item can be read with d[5] in every dictionary
4
A train number can be a key
Solution
Idea

Compare positions with keys.

  • 1, 2 and 4 are true. A dictionary has no positions (statement 3 is false).
  • Answer: options 1, 2 and 4.
Revision overview
ListValues by position
Walk past earlier items
DictionaryValues by key
Name or ID as key
What is a dictionaryWeek 7
Random accessSame time for any key
Size does not matter
Readingd[k]
chemMarks["Rahul"]
Revision: keys instead of positions
Next · DictionariesDictionary Basics: Create, Read, Write
02
Dictionaries

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:

literal.pseudo
{"Rahul":92, "Clarence":73, "Ritika":89}
chemMarkskeyvalue"Rahul"92"Clarence"73"Ritika"89chemMarks["Rahul"] → 92
Figure 2. chemMarks: three keys, three values

2.2The four basic operations

Empty dictionaryd = {}
You always start with an empty dictionary before adding anything to it.
Reading a values = sourceStation["10215"]
Square brackets around the key fetch the matching value.
Writing a valuechemMarks["Rahul"] = 92
If the key already exists, this replaces its value. If it does not, it creates a new key–value pair on the spot.
One ruleThe dictionary has to exist before you can add anything to it: always start with d = {} first.
before"Rahul"92"Ritika"89chemMarks["Rahul"] = 95"Rahul"95"Ritika"89key exists: value replacedchemMarks["Asha"] = 81"Rahul"95"Ritika"89"Asha"81new key: pair created
Figure 3. Writing to an existing key replaces its value; writing to a new key creates a pair

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:

chem-marks.pseudo
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}.

Keys must be unique (extra). If a second student called Rahul appears with 65, 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.
Reading a missing key (extra). Writing to a new key is fine, but reading 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

Exam tips
  • Trace a dictionary as a two-column table: key, value.
  • For every write, ask "does this key exist already?": replace or create.
Common mistakes
  • 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)

Q1Overwrite

Numerical Answer Type (NAT).

After d = {}, d["a"] = 1, d["b"] = 2, d["a"] = 5, what is d["a"]?

Solution
Idea

A write to an existing key replaces the value.

  • The last write to "a" stores 5.
  • Answer: 5
Q2How many keys?

Numerical Answer Type (NAT).

After the same four statements, how many keys does d have?

Solution
Idea

Replacing does not add a key.

  • The keys are "a" and "b".
  • Answer: 2
Q3Empty

Multiple Choice Question (MCQ): choose the one correct option.

Which statement creates an empty dictionary?

1
d = []
2
d = {}
3
d = 0
4
d = ""
Solution
Idea

Curly braces.

  • {} is an empty dictionary; [] is an empty list.
  • Answer: option 2.
Q4Same name

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"]?

1
92
2
65
3
157
4
Both 92 and 65
Solution
Idea

The later write replaces the earlier one.

  • The third row overwrites 92 with 65.
  • Answer: option 2.
Revision overview
Created = {}
Always first
Readv = d[k]
Key must exist
BasicsCreate, read, write
Writed[k] = v
Replace or create
From a tablechemMarks[name] = marks
Unique keys matter
Revision: the operations on a dictionary
Next · DictionariesLooping Through a Dictionary
03
Dictionaries

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.

The building block: keys(d)

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].

loop.pseudo
foreach k in keys(d) {
    Do something with d[k]
}
"Rahul"92"Clarence"73"Ritika"89keys(chemMarks)["Rahul""Clarence""Ritika"]foreach k in …chemMarks[k] → 92, 73, 89
Figure 4. keys(chemMarks) is a list; each key reads its value

3.2Example: the average Chemistry mark

Add up every value in the dictionary and divide by how many there are:

chem-average.pseudo
total = 0
count = 0
foreach k in keys(chemMarks) {
    total = total + chemMarks[k]
    count = count + 1
}
chemAvg = total / count
kchemMarks[k]totalcount
"Rahul"92921
"Clarence"731652
"Ritika"892543

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, count stays 0 and total / count divides by zero; check for this first.

3.4Exam tips and common mistakes

Exam tips
  • Write the keys list first, then trace one row per key.
Common mistakes
  • Writing foreach k in d: loop over keys(d).
  • Adding the keys instead of d[k].

Practice questions (graded-assignment style)

Q1Average

Numerical Answer Type (NAT).

For {"Rahul":92, "Clarence":73, "Ritika":89}, what is chemAvg? (Two decimal places.)

Solution
Idea

Sum of values over the number of keys.

  • (92 + 73 + 89) / 3 = 254 / 3.
  • Answer: 84.67
Q2keys

Multiple Choice Question (MCQ): choose the one correct option.

What does keys(chemMarks) return?

1
The list of marks
2
A dictionary
3
A list of the names
4
The number of keys
Solution
Idea

Only the keys.

  • A plain list of the keys; the values are read with chemMarks[k].
  • Answer: option 3.
Q3Total

Numerical Answer Type (NAT).

What is s after this code runs?

question.pseudo
d = {"x":4, "y":7, "z":9}
s = 0
foreach k in keys(d) {
    s = s + d[k]
}
Solution
Idea

Add the values.

  • 4 + 7 + 9 = 20.
  • Answer: 20
Revision overview
keys(d)A plain list of keys
No positions in d
Loopingkeys(d)
Averagetotal + d[k]
254 / 3 ≈ 84.67
Revision: looping through a dictionary by its keys
Next · DictionariesChecking If a Key Exists
04
Dictionaries

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?

The building block: isKey(d, k)

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:

runs.pseudo
if (isKey(runs, "Kohli")) {
    runs["Kohli"] = runs["Kohli"] + score
}
else {
    runs["Kohli"] = score
}
score arrivesisKey(runs, "Kohli")?Trueadd to the totalruns[k] = runs[k] + scoreFalsestart the totalruns[k] = score
Figure 5. One decision per score: add, or start the total
Match scoreisKey(runs, "Kohli")Branchruns["Kohli"] after
45Falseelse: start45
12Trueadd57
78Trueadd135

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

isKey.pseudo
Procedure isKey(D, k)
    found = False
    foreach key in keys(D) {
        if (key == k) {
            found = True
            exitloop
        }
    }
    return(found)
End isKey
simple isKey: check key after key"Rahul""Clarence""Ritika""Asha""Kiran"comparisons grow with the sizereal dictionary: jump straight to the key"Ritika""Ritika"constant time
Figure 6. The simple isKey walks the keys; a real dictionary jumps to the key

On 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.

Constant time

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 score with 1 and the pattern counts occurrences instead of adding amounts.

4.5Exam tips and common mistakes

Exam tips
  • Trace with columns: the item, isKey, the branch, the value after.
Common mistakes
  • Updating without checking, which reads a missing key the first time.
  • Swapping the branches: setting d[k] = v when the key exists throws away the total.

Practice questions (graded-assignment style)

Q1Counting words

Numerical Answer Type (NAT).

What is count["a"] after this code?

question.pseudo
count = {}
foreach w in ["a", "b", "a", "c", "a"] {
    if (isKey(count, w)) {
        count[w] = count[w] + 1
    }
    else {
        count[w] = 1
    }
}
Solution
Idea

The pattern with v = 1.

  • "a" appears three times: 1, then 2, then 3.
  • Answer: 3
Q2Keys after counting

Numerical Answer Type (NAT).

For the same code, how many keys does count have at the end?

Solution
Idea

One key per distinct word.

  • "a", "b" and "c".
  • Answer: 3
Q3The simple isKey

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?

Solution
Idea

No match, no exitloop.

  • Every key is compared once.
  • Answer: 5
Q4The else branch

Multiple Choice Question (MCQ): choose the one correct option.

In the accumulator pattern, when does d[k] = v (the else branch) run?

1
Every time
2
The first time k is seen
3
The last time k is seen
4
Never
Solution
Idea

isKey is False.

  • Only the first time k is seen; afterwards k is a key.
  • Answer: option 2.
Revision overview
isKey(d, k)True if k is a key
AccumulatorExists: add
New: create
isKeyRunning totals
Simple versionWalk the keys
exitloop on a match
Real dictionariesConstant time
Used from now on
Revision: checking a key before updating it
Next · Worked exampleCounting Food Purchases
05
Worked example

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.

food.pseudo
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.Items is the list of items in one order; each item has a Category.
  • The inner foreach goes through those items, so one order can add several to the count.
  • Once every row has been processed, foodD holds each customer's total food item count.

5.2A run on five orders (illustrative)

order (customer, item categories)foodD after the orderAhmedFoodStationeryFoodAhmed2BhuvanToiletriesAhmed2AhmedFoodAhmed3CharuFoodFoodAhmed3Charu2BhuvanFoodAhmed3Charu2Bhuvan1
Figure 7. foodD after each order; only Food items count
OrderCustomerItemsFood itemsfoodD after
1AhmedFood, Stationery, Food2{"Ahmed":2}
2BhuvanToiletries0{"Ahmed":2}
3AhmedFood1{"Ahmed":3}
4CharuFood, Food2{"Ahmed":3, "Charu":2}
5BhuvanFood1{"Ahmed":3, "Charu":2, "Bhuvan":1}
Bhuvan after order 2. Bhuvan's first order has no Food item, so the inner 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):

top-customer.pseudo
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 foodD alone.
  • Ties (extra). With a strict > the first customer reached with the top count is kept; since the order of keys is not fixed, report all customers with maxCount if ties matter.
  • Names as keys (extra). Two different customers with the same name would be counted together.

5.5Exam tips and common mistakes

Exam tips
  • Count Food items per order first, then add to the customer's running total.
Common mistakes
  • Adding 1 per order instead of per Food item.
  • Assuming every customer is a key.

Practice questions (graded-assignment style)

Q1Ahmed's count

Numerical Answer Type (NAT).

In the five-order run, what is foodD["Ahmed"] at the end?

Solution
Idea

Count his Food items over both orders.

  • 2 in order 1, 1 in order 3.
  • Answer: 3
Q2Keys after order 2

Numerical Answer Type (NAT).

How many keys does foodD have after the first two orders?

Solution
Idea

Bhuvan bought no food yet.

  • Only "Ahmed".
  • Answer: 1
Q3The top customer

Multiple Choice Question (MCQ): choose the one correct option.

Which statement finds the customer with the most food items once foodD is built?

1
Read foodD[1]
2
Loop over keys(foodD) keeping the largest foodD[c]
3
Take first(keys(foodD))
4
Use isKey(foodD, "Food")
Solution
Idea

Loop over the keys.

  • A max loop over keys(foodD) comparing foodD[c].
  • Answer: option 2.
Q4foodD facts

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements.

1
A customer becomes a key with their first Food item
2
Each order adds at most 1
3
Customers with no Food item are not keys
4
foodD has one key per order
Solution
Idea

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.
Revision overview
BuildKey: customer
Food item: +1 or start at 1
Food purchasesfoodD
AnswerMax over keys(foodD)
Ahmed: 3
Revision: a dictionary of counts, then a max over its keys
Next · Worked exampleThe Birthday Paradox
06
Worked example

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.pseudo
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
}
Dictionary of dictionaries

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.

Why the else branch creates {} first. Writing 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)

SeqNoDoBisKey(birthdays, dob)What happens
012 MarFalsenew inner {0}
15 JulFalsenew inner {1}
212 MarTrueduplicate; add 2
321 OctFalsenew inner {3}
45 JulTrueduplicate; add 4
530 JanFalsenew inner {5}
612 MarTrueduplicate; add 6
79 SepFalsenew inner {7}
birthdaysa dictionary of dictionaries"12 Mar"{0True2True6True}"5 Jul"{1True4True}"21 Oct"{3True}"30 Jan"{5True}"9 Sep"{7True}duplicates"12 Mar"True"5 Jul"True
Figure 8. birthdays after all eight rows; duplicates holds the two shared dates

To list the students who share each date (extra; the slide stops at building the dictionaries):

list-sharers.pseudo
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):

PeopleChance that at least two share a birthday
2350.7%
3070.6%
4089.1%
5097.0%
7099.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)

comparisons for 8 studentsfor 30 students28compare every pair (Week 4)8one dictionary lookup per student435compare every pair (Week 4)30one dictionary lookup per student
Figure 9. Comparisons: every pair (Week 4) against one dictionary lookup per student

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 DoB also 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] = True runs again; writing the same value again changes nothing.

6.6Exam tips and common mistakes

Exam tips
  • Trace with a table: date, isKey, and the inner dictionary after the row.
Common mistakes
  • Writing birthdays[dob][seqno] before birthdays[dob] = {}.
  • Counting a date as a duplicate the first time it is seen.

Practice questions (graded-assignment style)

Q1Shared dates

Numerical Answer Type (NAT).

In the eight-student run, how many keys does duplicates have?

Solution
Idea

Dates seen more than once.

  • "12 Mar" and "5 Jul".
  • Answer: 2
Q2The inner dictionary

Numerical Answer Type (NAT).

How many keys does the inner dictionary birthdays["12 Mar"] have?

Solution
Idea

Students born on 12 Mar.

  • SeqNos 0, 2 and 6.
  • Answer: 3
Q3Every pair

Numerical Answer Type (NAT).

How many comparisons would comparing every pair of the eight students need?

Solution
Idea

½ × N × (N − 1).

  • 8 × 7 / 2 = 28.
  • Answer: 28
Q4The else branch

Multiple Choice Question (MCQ): choose the one correct option.

Why does the else branch run birthdays[dob] = {} before birthdays[dob][seqno] = True?

1
To delete old data
2
To mark the date as a duplicate
3
The inner dictionary must exist before a key is added to it
4
It is not needed
Solution
Idea

One level down, the same rule.

  • The inner dictionary must exist before anything is written into it.
  • Answer: option 3.
Revision overview
BuildKey: date of birth
Value: dict of SeqNos
DuplicatesSeen again: True
Shared dates only
BirthdaysNested dictionaries
Paradox23 people: 50.7%
30 people: 70.6%
CostN lookups
not N(N−1)/2
Revision: grouping by date with a dictionary of dictionaries
Next · Worked exampleResolving Pronouns
07
Worked example

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:

part-of-speech.pseudo
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.

match-pronouns.pseudo
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).

The1teacher2praised3Asha4because5she6worked7hard8nounpronounmatched
Figure 10. she (6) is matched to Asha (4), the nearest noun before it
pnn < p?matched
62yes2
64yes4
(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".

Rahul1gave2Ritika3a4book5and6she7thanked8him9nounpronounmatched
Figure 11. The nearest-noun rule matches both pronouns to "book"
A heuristic (extra). The nearest noun before a pronoun is a rule of thumb, not grammar. It ignores gender, number and meaning, so "she" can be matched to "book". It works on the first sentence and fails on the second; a better resolver would also check that the noun can agree with the pronoun.

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

Exam tips
  • List the noun and pronoun serial numbers first.
  • For each pronoun, the answer is the largest noun number smaller than it.
Common mistakes
  • Taking the nearest noun after the pronoun.
  • Forgetting matched = -1 for each pronoun.

Practice questions (graded-assignment style)

Q1Nearest noun

Numerical Answer Type (NAT).

Nouns are at [2, 4] and the pronoun is at 6. What is matchD[6]?

Solution
Idea

The largest noun number below 6.

  • Noun 4.
  • Answer: 4
Q2No noun before

Numerical Answer Type (NAT).

In "She met Ravi" (She = 1, Ravi = 3, a noun), what is matchD[1]?

Solution
Idea

No noun comes before 1.

  • The first noun is 3, not below 1, so the loop exits with matched = -1.
  • Answer: -1
Q3Comparisons

Numerical Answer Type (NAT).

Nouns [1, 3, 5], pronouns [7, 9]. How many times is n < p evaluated?

Solution
Idea

No exitloop happens.

  • 3 for pronoun 7, 3 for pronoun 9.
  • Answer: 6
Q4The method

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements.

1
The values of partOfSpeech are lists
2
Both lists are in ascending order
3
exitloop is safe because the noun list is sorted
4
The nearest noun is always the correct referent
Solution
Idea

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.
Revision overview
BucketspartOfSpeech["Noun"]
partOfSpeech["Pronoun"]
Lists, ascending
PronounsmatchD
MatchingLast noun with n < p
exitloop otherwise
-1 if none
CautionA heuristic
she → book is possible
Revision: a dictionary of lists and the nearest-noun rule
Next · All topicsWeek 7 Summary Sheet
08
All topics

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

OperationMeaning
d = {}Create an empty dictionary
d[k] = vAdd 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

The accumulator pattern
Worth memorising
pseudocode
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.

  1. Check isKey(d, k).
  2. If it exists, add v to d[k].
  3. Otherwise start it: d[k] = v (v = 1 to count).
ExampleWords a, b, a, c, a with v = 1 give a: 3, b: 1, c: 1.
Fill a dictionary from a table
One key per row
pseudocode
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.

  1. Start with d = {}.
  2. Write d[key] = value for each row.
  3. Use a unique field as the key, or values are overwritten.
ExampleRows Rahul 92, Clarence 73, Ritika 89 give three pairs.
Loop over the keys
Sum and count
pseudocode
foreach k in keys(d) {
    total = total + d[k]
    count = count + 1
}

Use whenYou need every value: totals, averages, a maximum.

  1. Get the list with keys(d).
  2. Read each value with d[k].
  3. Do not rely on the order of the keys.
Example92, 73, 89: total 254, average ≈ 84.67.
A dictionary inside a dictionary
Group by a key
pseudocode
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).

  1. Create the inner dictionary the first time g is seen.
  2. Add the id into groups[g].
  3. keys(groups[g]) lists the members.
ExampleEight students: "12 Mar" holds 0, 2, 6 and "5 Jul" holds 1, 4.
Lists as values
Buckets
pseudocode
d["Noun"] = []
d["Pronoun"] = []
d["Noun"] = d["Noun"] ++ [X.SerialNo]

Use whenItems fall into a few named buckets and order matters inside each.

  1. Create each bucket as an empty list.
  2. Append with ++.
  3. Read a bucket like any list.
ExampleNouns [1, 3, 5] and pronouns [7, 9] for "Rahul gave Ritika a book and she thanked him".
Maximum over the keys
Top value
pseudocode
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.

  1. Start the maximum at 0.
  2. Loop over keys(d), keeping the key with the largest d[k].
  3. Decide what to do with ties.
ExamplefoodD = Ahmed 3, Charu 2, Bhuvan 1 gives Ahmed.

Which tool when?

SituationTool
Find the value for a name or IDd[k]
Keep a total per keyThe accumulator pattern with isKey
Go through all valuesforeach k in keys(d)
Group items by a shared valueA dictionary of dictionaries (or of lists)
Find items that share a valueOne pass with a dictionary, not every pair
Collect items per category, in orderA dictionary whose values are lists
Why dictionaries matter

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

No d = {} first
  • The dictionary must exist before anything is written into it, at every level of nesting.
Reading a missing key
  • Check isKey before reading d[k] in a running total.
Write means add
  • Writing to an existing key replaces its value; it never creates a second pair.
Non-unique keys
  • Two students with the same name overwrite each other; key by SeqNo.
Looping over d
  • Loop over keys(d), and do not depend on its order.
Trusting the heuristic
  • The nearest noun is a rule of thumb; it can match "she" to "book".
Back to top