Neural Sync Active
Week 6: Dictionary Applications
Registry Synced
Week 6: Dictionary Applications
1511 words
8 min read
Reading compass
Now · 1. Motivation: Real-World Dictionary Problems
Week 6: Dictionary Applications
BSCS1001 — IIT Madras BS Degree Prerequisite: Topic 11 (Dictionaries) Cross-links: BSCS1002-Python (Week 8 — Dictionaries)
1. Motivation: Real-World Dictionary Problems
Dictionaries are powerful because they provide O(1) lookup — instant access to any value given its key. This speed enables elegant solutions to problems that would otherwise require complex nested iterations.
Problems That Benefit from Dictionaries
| Problem | Without Dictionary | With Dictionary |
|---|---|---|
| Find shared birthdays | O(N²) nested loops | O(N) single pass |
| Match pronouns to nouns | Complex sorting & scanning | O(N) with key-value mapping |
| Track customer purchases | Multiple separate lists | Single dictionary |
| Find common elements | Nested foreach | Dictionary lookup |
Key Insight: If you find yourself writing nested loops to find matches, ask: "Could I use a dictionary instead?"
2. Birthday Paradox with Dictionaries Revisited
The Problem
Find all pairs of students who share the same birthday.
Dictionary Solution
pseudoProcedure FindSharedBirthdays() { 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 } return(duplicates) End FindSharedBirthdays
Comparison of Approaches
| Method | Complexity | Code Length | When to Use |
|---|---|---|---|
| Nested iteration | O(N²) | Short | Very small N (<50) |
| Binning | O(N²/K) | Medium | Natural bins exist |
| Dictionary | O(N) | Short | Always — best for most cases |
3. Pronoun Resolution
Problem
In a paragraph, each pronoun (he, she, it) refers to the nearest preceding noun. Given a list of words with their parts of speech, match each pronoun to its noun.
MCQ
3 Unit Assessment
Reference-only archive item
The completed export preserved the prompt as an image but not a reusable answer key. The reconstruction below is for study, not scoring.
Study reconstruction
// Step 1: Collect nouns and pronouns with their positions
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
}
// Step 2: Match each pronoun to nearest preceding noun
matchD = {}
foreach p in partOfSpeech["Pronoun"] {
matched = -1
foreach n in partOfSpeech["Noun"] {
if (n < p) {
matched = n
}
else {
exitloop // Nouns are sorted, no need to continue
}
}
matchD[p] = matched
}
Why Dictionaries Help
The dictionarypartOfSpeech organizes words by their grammatical role, allowing us to:
- Access all nouns and pronouns as sorted lists
- Iterate through pronouns and find the nearest preceding noun
- Store results in
matchDfor easy lookup
4. Customer Spending Analysis
Problem
Track total spending per customer from a shopping bill dataset.
MCQ
3 Unit Assessment
Reference-only archive item
The completed export preserved the prompt as an image but not a reusable answer key. The reconstruction below is for study, not scoring.
Study reconstruction
spending = {}
while (Table 1 has more rows) {
Read the first row X in Table 1
customer = X.CustomerName
amount = X.Amount
if (isKey(spending, customer)) {
spending[customer] = spending[customer] + amount
}
else {
spending[customer] = amount
}
Move X to Table 2
}
// Find top spender
maxSpend = 0
topCustomer = ""
foreach c in keys(spending) {
if (spending[c] > maxSpend) {
maxSpend = spending[c]
topCustomer = c
}
}
Tracking Food Items Separately
foodD = {}
while (Table 1 has more rows) {
Read the first row X in Table 1
customer = X.CustomerName
items = X.Items
for each 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
}
5. Finding Common Elements Across Dictionaries
Intersection of Two Dictionaries
pseudoProcedure DictIntersection(d1, d2) { result = {} foreach k in keys(d1) { if (isKey(d2, k)) { result[k] = d1[k] } } return(result) End DictIntersection
Comparing Train Routes
Two trains have lists of stations. Find common stations:
pseudo// Represent routes as dictionaries for O(1) lookup route1Dict = {} foreach s in route1 { route1Dict[s] = True } common = [] foreach s in route2 { if (isKey(route1Dict, s)) { common = common ++ [s] } }
6. Dictionary with Lists as Values
Students per City
pseudocityStudents = {} while (Table 1 has more rows) { Read the first row X city = X.City if (isKey(cityStudents, city)) { cityStudents[city] = cityStudents[city] ++ [X.Name] } else { cityStudents[city] = [X.Name] } Move X } // Result: {"Chennai": ["Alice", "Charlie"], "Mumbai": ["Bob"]}
Mentors per Student (from Week 7)
pseudomentors = {} foreach j in students { mentors[j] = {} foreach i in students { if (canMentor(i, j)) { mentors[j][i] = True } } } // mentors[j] is a dictionary of student j's mentors // Length of keys gives mentor count
7. Side Effects with Dictionaries
Deleting a Key: With vs Without Side Effects
With side effect (modifies original):
sqlProcedure DeleteKey(d, k) { foreach key in keys(d) { if (k == key) { remove key from d } } }
Without side effect (returns new dictionary):
pseudoProcedure DeleteKey2(d, k) { myd = {} foreach key in keys(d) { if (k ≠ key) { myd[key] = d[key] } } return(myd) End DeleteKey2 // Caller must reassign: myd = DeleteKey2(myd, k)
Why Avoid Side Effects with Dictionaries?
If a procedure modifies a dictionary that the caller is also using, the caller might:
- Lose data (keys unexpectedly removed)
- Get wrong results (values changed)
- Encounter race conditions (concurrent access)
Best practice: Unless the modification IS the goal (e.g.,
addStudent), return a new dictionary.
8. Practice Questions
Basic Questions
Q1. What is the main advantage of using a dictionary to find shared birthdays compared to nested iterations?
Show AnswerDictionaries provide O(1) lookup per key, reducing the algorithm from O(N²) to O(N). A single pass through the data is all that's needed. Q2. In the pronoun resolution problem, why are the noun and pronoun lists sorted? Show AnswerThe lists are sorted by SerialNo (position in the paragraph). This allows us to efficiently find the nearest preceding noun for each pronoun — we iterate through nouns until we pass the pronoun's position, then exit the loop. Q3. Write pseudocode to build a dictionary mapping product names to their total quantity sold. Show AnswerpseudoproductQty = {} while (Table 1 has more rows) { Read X if (isKey(productQty, X.ProductName)) { productQty[X.ProductName] = productQty[X.ProductName] + X.Quantity } else { productQty[X.ProductName] = X.Quantity } Move X }
Q4. What is the difference between
DeleteKey (with side effect) and DeleteKey2 (without side effect)?Show AnswerDeleteKeymodifies the original dictionary directly.DeleteKey2creates and returns a new dictionary with the key removed, leaving the original unchanged. The caller must reassign the variable if they want the updated dictionary.
Intermediate Questions
Q5. Trace the birthday paradox algorithm for dataset:
- A: DOB=50, B: DOB=120, C: DOB=50, D: DOB=50, E: DOB=120
Show Answer
| Row | DOB | isKey? | birthdays after | duplicates after |
|---|---|---|---|---|
| A | 50 | ❌ | {50: {A: T}} | {} |
| B | 120 | ❌ | {50: {A}, 120: {B}} | {} |
| C | 50 | ✅ | {50: {A, C}, 120: {B}} | {50: T} |
| D | 50 | ✅ | {50: {A, C, D}, 120: {B}} | {50: T} |
| E | 120 | ✅ | {50: {A, C, D}, 120: {B, E}} | {50: T, 120: T} |
Duplicates found: DOB 50 and 120 Q6. How would you modify the pronoun resolver to handle cases where a pronoun has no preceding noun? Show AnswerInitializematched = -1and only add tomatchDifmatched ≠ -1:pseudoforeach p in partOfSpeech["Pronoun"] { matched = -1 foreach n in partOfSpeech["Noun"] { if (n < p) { matched = n } else { exitloop } } if (matched ≠ -1) { matchD[p] = matched } // If matched == -1, no noun precedes this pronoun }
Q7. Why does the
cityStudents example use a list as the dictionary value?Show AnswerEach city maps to MULTIPLE students. A dictionary value can only hold one value per key, so we use a list to store all students from that city. The dictionary key is the city name, and the value is a list of student names. Q8. Write a procedure to invert a dictionary (swap keys and values). Assume all values are unique. Show AnswerpseudoProcedure InvertDict(d) { inverted = {} foreach k in keys(d) { v = d[k] inverted[v] = k } return(inverted) End InvertDict // Example: InvertDict({"a": 1, "b": 2}) → {1: "a", 2: "b"}
📚 Cross-References
| Course | Topic | Connection |
|---|---|---|
| BSCS1002 (Python) | Week 8 — Dictionaries | Python dict operations |
| BSCS1002 (Python) | Week 9 — Dictionary apps | Real-world dictionary use |
Next Topic: 13 — Graphs IntroductionQuiz Tip: Dictionary problems are common in Quiz 2 and End Term. Practice the "isKey + create/update" pattern! Join Discord PreviousDictionariesNextGraphs & Adjacency Matrices