Quiz 2

Week 6: Dictionary Applications

1511 words
8 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# 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 give...

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

ProblemWithout DictionaryWith Dictionary
Find shared birthdaysO(N²) nested loopsO(N) single pass
Match pronouns to nounsComplex sorting & scanningO(N) with key-value mapping
Track customer purchasesMultiple separate listsSingle dictionary
Find common elementsNested foreachDictionary 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

pseudo
Procedure 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

MethodComplexityCode LengthWhen to Use
Nested iterationO(N²)ShortVery small N (<50)
BinningO(N²/K)MediumNatural bins exist
DictionaryO(N)ShortAlways — 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 dictionary partOfSpeech 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 matchD for 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

pseudo
Procedure 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

pseudo
cityStudents = {}
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)

pseudo
mentors = {}
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):
sql
Procedure DeleteKey(d, k) {
    foreach key in keys(d) {
        if (k == key) {
            remove key from d
        }
    }
}
Without side effect (returns new dictionary):
pseudo
Procedure 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:
  1. Lose data (keys unexpectedly removed)
  2. Get wrong results (values changed)
  3. 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 Answer
Dictionaries 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 Answer
The 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 Answer
pseudo
productQty = {}
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 Answer
DeleteKey modifies the original dictionary directly. DeleteKey2 creates 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
RowDOBisKey?birthdays afterduplicates after
A50{50: {A: T}}{}
B120{50: {A}, 120: {B}}{}
C50{50: {A, C}, 120: {B}}{50: T}
D50{50: {A, C, D}, 120: {B}}{50: T}
E120{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 Answer
Initialize matched = -1 and only add to matchD if matched ≠ -1:
pseudo
foreach 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 Answer
Each 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 Answer
pseudo
Procedure 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

CourseTopicConnection
BSCS1002 (Python)Week 8 — DictionariesPython dict operations
BSCS1002 (Python)Week 9 — Dictionary appsReal-world dictionary use

Quiz Tip: Dictionary problems are common in Quiz 2 and End Term. Practice the "isKey + create/update" pattern! Join Discord PreviousDictionariesNextGraphs & Adjacency Matrices
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.