Week 6: Tables & Dictionaries

3549 words
18 min read
2026-09-12T00:00:00.000Z
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

Tabular records, fields, keys, dictionaries, constant-time lookup, and grouping/frequency counting with dictionaries. # Computational Thinking — Week 6: Tables & Dictionaries IITM’s CT Week 6 covers **Tables and Dictionaries**.

Computational Thinking — Week 6: Tables & Dictionaries

IITM’s CT Week 6 covers Tables and Dictionaries.
The syllabus only names the topics, so the detailed notes below expand those concepts in the style used throughout the course.

TL;DR

Week 5 dealt with a one-dimensional structure:
text
List
[10, 20, 30]
Week 6 introduces richer organization:

Table

text
Student | Marks | City
A       | 80    | Delhi
B       | 65    | Pune
A table organizes data into:
  • rows
  • columns
  • records
  • fields

Dictionary

text
{
    "A": 80,
    "B": 65
}
A dictionary stores:
key→value\boxed{ \text{key}\rightarrow\text{value} }
The central Week 6 mental model is:
structured data→lookup→update→aggregate\boxed{ \text{structured data} \rightarrow \text{lookup} \rightarrow \text{update} \rightarrow \text{aggregate} }

1. From lists to tables

A list stores a sequence:
text
[72, 84, 91]
But real datasets often contain multiple attributes per item.
For example:
text
Name, Age, Marks
A table lets us represent such structured records.

2. Table

A table is a collection of rows and columns.
Example:
NameAgeMarks
A2075
B1988
C2164

3. Row

A row usually represents one record/entity.
For example:
text
A, 20, 75
is one student's record.
So:
row=one observation / record\boxed{ \text{row} = \text{one observation / record} }

4. Column

A column represents one attribute/field measured across records.
Examples:
  • Name
  • Age
  • Marks
So:
column=one variable / attribute\boxed{ \text{column} = \text{one variable / attribute} }
This connects directly to Stats Week 1:
  • rows = observations
  • columns = variables

5. Cell

A single intersection of a row and column is a cell.
Example:
For student B:
text
Marks = 88
That individual value occupies one cell.

6. Record

A record is all information associated with one entity.
Example:
text
{Name: B, Age: 19, Marks: 88}
Conceptually, a row and a record are closely related.

7. Field

A field is one named component of a record.
For:
text
{Name: B, Age: 19, Marks: 88}
fields are:
text
Name
Age
Marks

8. Iterating through a table

Suppose we want average marks.
Conceptually:
text
total = 0
count = 0

for each row in table:
    total = total + row.Marks
    count = count + 1
Then:
average=totalcount\text{average} = \frac{total}{count}
This is simply Week 1 iteration applied to structured records.

9. Filtering rows

Suppose we want students with:
text
Marks > 70
Pseudocode:
text
for each row:
    if row.Marks > 70:
        process row
Here the condition checks one field of the current row.

10. Multiple conditions

Suppose we want:
students older than 18 and marks above 70.
text
if row.Age > 18 AND row.Marks > 70:
This combines tables with Week 2–3 Boolean logic.

11. Selecting columns

Sometimes we do not need the whole record.
Example:
From:
NameAgeMarks
A2075
we may only need:
text
Name
Marks
Conceptually, selecting columns extracts only relevant fields.

12. Updating a table

A table may be mutable.
Example:
text
row.Marks = row.Marks + 5
updates one field in a record.
As with list updates, later computation sees the new value.

13. Example update

Before:
NameMarks
A75
B88
Suppose A gets bonus 5.
After:
NameMarks
A80
B88
Only one cell changed.

14. Finding maximum in a table

Suppose we want highest marks.
text
max_marks = first_row.Marks

for each remaining row:
    if row.Marks > max_marks:
        max_marks = row.Marks
Same max pattern as Week 2.

15. Finding the record associated with maximum

Sometimes you need not only the maximum value, but also the student who achieved it.
Then maintain:
text
best_marks
best_name
or entire best row.
Conceptually:
text
best_row = first row

for each row:
    if row.Marks > best_row.Marks:
        best_row = row

16. Why storing the whole row helps

Suppose max is:
95.95.
If you only store:
text
max_marks = 95
you may lose information about:
  • who scored 95
  • their city
  • their age
Storing the full row preserves the associated record.

17. Table ordering

Tables may or may not have an inherent meaningful row order.
That depends on the problem.
A list's order is central.
A table is often more about structured records than positional meaning.

18. Dictionary

A dictionary stores mappings:
key→value\boxed{ \text{key}\rightarrow\text{value} }
Example:
text
marks = {
    "A": 75,
    "B": 88,
    "C": 64
}
Here:
  • "A" is a key
  • 75 is its value

19. Key

A key identifies an entry.
Example:
text
marks["B"]
conceptually gives:
text
88
The key tells us which stored value we want.

20. Value

A value is the information associated with a key.
Example:
text
"B" → 88
So:
key = identifier\boxed{ \text{key = identifier} } value = associated data\boxed{ \text{value = associated data} }

21. Why dictionaries are useful

Suppose you have:
text
student_id → marks
Without a dictionary, you might scan an entire list to find one student's score.
With a dictionary, conceptually you can directly ask:
text
marks[id]
This makes key-based lookup natural.

22. Example

text
population = {
    "Delhi": 20,
    "Mumbai": 18,
    "Pune": 7
}
Then:
text
population["Mumbai"]
returns:
text
18
Conceptually.

23. Keys are typically unique

A dictionary normally uses each key once.
Bad conceptual mapping:
text
"A" → 50
"A" → 80
Which value would "A" mean?
So dictionary keys identify entries uniquely.

24. Values need not be unique

This is fine:
text
"A" → 80
"B" → 80
"C" → 65
Different keys may map to the same value.
Uniqueness matters for keys, not necessarily values.

25. Dictionary lookup

Conceptually:
text
D[key]
means:
return the value associated with key.
Example:
text
D = {"x": 4, "y": 9}
Then:
text
D["x"]
gives:
4.4.

26. Updating dictionary values

Suppose:
text
count["apple"] = 3
and another apple appears.
Update:
text
count["apple"] = count["apple"] + 1
Now:
text
count["apple"] = 4
This is exactly the accumulator pattern from Week 1, but indexed by key.

27. Frequency counting with dictionary

Suppose data:
text
A, B, A, C, A, B
We want frequency of each value.
A dictionary can represent:
text
A → 3
B → 2
C → 1
This is one of the most important dictionary patterns.

28. Frequency-count pseudocode

Conceptually:
text
freq = empty dictionary

for each x:
    if x already exists in freq:
        freq[x] = freq[x] + 1
    else:
        freq[x] = 1
After processing all items, each key stores its count.

29. Trace frequency counting

Input:
text
A, B, A, C, A
Progress:
text
A
{A:1}
then:
text
B
{A:1, B:1}
then:
text
A
{A:2, B:1}
then:
text
C
{A:2, B:1, C:1}
then:
text
A
{A:3, B:1, C:1}
Final:
A:3, B:1, C:1\boxed{ A:3,\ B:1,\ C:1 }

30. Dictionary as generalized counter

Earlier:
text
count = 0
tracked one category.
Now:
text
freq[key]
lets us maintain many counters simultaneously.
This is a major abstraction jump.

31. Example: word frequencies

Input:
text
cat dog cat bird dog cat
Dictionary:
text
cat  → 3
dog  → 2
bird → 1
This pattern appears constantly in data processing.

32. Example: scores by student

text
scores = {
    "A": 72,
    "B": 91,
    "C": 68
}
This is different from a frequency dictionary.
The value can represent any associated information, not just counts.

33. Dictionary values can be complex

A value could itself be a record:
text
students = {
    "A": {age:20, marks:80},
    "B": {age:19, marks:75}
}
So dictionaries can organize structured data hierarchically.

34. Table vs dictionary

A table naturally represents many records with the same fields.
Example:
IDAgeMarks
A2080
B1975
A dictionary naturally represents lookup by a unique key:
text
A → record
B → record
They can represent related information in different forms.

35. Converting table to dictionary conceptually

Table:
IDMarks
A80
B75
Dictionary:
text
{
    A: 80,
    B: 75
}
If ID uniquely identifies each row, it can serve naturally as a dictionary key.

36. Lookup vs scan

Suppose there are many student rows.
To find student "S123" in a plain table/list, a simple algorithm may scan:
text
row 1
row 2
row 3
...
A dictionary is conceptually designed for direct key lookup.
This is the key structural advantage.

37. Membership test

Before accessing a dictionary key, sometimes ask:
text
does key exist?
This avoids trying to retrieve a value for a missing key.
Conceptually:
text
if key exists in D:
    ...
else:
    ...

38. Missing-key problem

Suppose:
text
D = {"A": 5}
and algorithm asks:
text
D["B"]
But "B" does not exist.
Depending on the computational model, this may be invalid/error-like behavior.
So key existence matters.

39. Safe update pattern

For frequency counting:
text
if x exists:
    freq[x] = freq[x] + 1
else:
    freq[x] = 1
The else handles first occurrence.

Common mistake: initialize new frequency to 0
Suppose first occurrence of "A" is encountered.
If you do:
text
freq["A"] = 0
and stop there, you have failed to count that occurrence.
Typically first occurrence should produce:
text
freq["A"] = 1

Common mistake: reset count each time
Wrong:
text
for each x:
    freq[x] = 1
This means repeated occurrences always overwrite with 1.
Correct logic increments an existing entry.

Common mistake: key vs value confusion
Given:
text
D = {"A": 80}
"A" is not the value.
It is the key.
80 is the value.
Keep this distinction precise.

Common mistake: assume values are unique
Two students may both score:
80.80.
That does not violate dictionary structure if their keys are distinct.

44. Iterating over dictionary entries

Conceptually, one may iterate over:
  • keys
  • values
  • key-value pairs
Example:
text
for each key in D:
    process key and D[key]

45. Example: find key with largest value

Suppose:
text
D = {
    A: 70,
    B: 92,
    C: 85
}
Goal:
find student with highest marks.
Conceptually:
text
best_key = first key

for each key:
    if D[key] > D[best_key]:
        best_key = key
Final:
text
B
with value:
92.92.

46. Why store key, not only max value

If you store only:
text
max = 92
you know the score but not who achieved it.
Instead:
text
best_key = B
lets you recover:
text
D[B] = 92

47. Dictionary and binning connection

Suppose bin labels are:
text
low
medium
high
Instead of separate variables:
text
low = 0
medium = 0
high = 0
you can conceptually use:
text
bins["low"]
bins["medium"]
bins["high"]
A dictionary generalizes the bin-count pattern.

48. Example

Data:
text
4, 12, 8, 21
Bins:
text
low    → 0
medium → 0
high   → 0
After processing:
text
low    → 2
medium → 1
high   → 1
Same result as Week 4, but organized as key-value state.

49. Grouping by key

Suppose records:
CitySales
A10
B20
A15
B5
We want total sales per city.
Dictionary:
text
A → 25
B → 25
This is a powerful pattern:
group by key→aggregate values\boxed{ \text{group by key} \rightarrow \text{aggregate values} }

50. Group-sum pseudocode

Conceptually:
text
totals = empty dictionary

for each row:
    city = row.City

    if city not in totals:
        totals[city] = 0

    totals[city] = totals[city] + row.Sales
This combines:
  • tables
  • dictionaries
  • iteration
  • selection
  • accumulation

51. Group-count pattern

To count number of records per category:
text
counts[key] = counts[key] + 1
Example:
Department
CS
Math
CS
Physics
CS
Result:
text
CS      → 3
Math    → 1
Physics → 1

52. Group-average pattern

To find average per category, maintain two dictionaries:
text
sum[key]
count[key]
Then:
average[key]=sum[key]count[key]\boxed{ average[key] = \frac{sum[key]}{count[key]} }
This is a very general data-analysis pattern.

53. Example

Records:
text
A: 10
A: 20
B: 30
Maintain:
text
sum[A] = 30
count[A] = 2

sum[B] = 30
count[B] = 1
Then:
avg[A]=15avg[A]=15 avg[B]=30.avg[B]=30.

54. Table filtering + dictionary aggregation

Suppose:
Count passing students per department.
For each row:
  1. check:
    text
    Marks >= 40
    
  2. if true:
    text
    pass_count[Department]++
    
This is a realistic multi-concept algorithm.

55. Example

DeptMarks
CS80
Math35
CS55
Math60
Passing:
text
CS   → 2
Math → 1

56. Table as list of records

A useful mental model is:
text
Table
=
list of rows
where each row itself contains named fields.
Conceptually:
text
[
  {Name:A, Marks:80},
  {Name:B, Marks:70}
]
This helps connect Week 5 lists with Week 6 tables.

57. Dictionary as function-like mapping

A dictionary behaves conceptually like a finite mapping:
f:keys→valuesf:\text{keys}\to\text{values}
For example:
f(A)=80.f(A)=80.
This resembles a mathematical function where each valid key maps to one value.

58. But dictionary is stored data

Unlike an abstract mathematical function, a dictionary is typically mutable state.
You may do:
text
D[A] = 80
then later:
text
D[A] = 90
The stored mapping changes.

59. Updating based on previous value

Suppose:
text
balance["A"] = 100
Then deposit 50:
text
balance["A"] = balance["A"] + 50
Result:
text
balance["A"] = 150
Same assignment semantics as ordinary variables.

60. Nested dictionaries/tables intuition

You may encounter structures conceptually like:
text
D[city][year]
or:
text
student[id].marks
Do not let notation distract you.
Resolve it layer by layer:
  1. locate outer key/record
  2. locate inner field/key
  3. read/update value

61. Trace example

Start:
text
D = empty
Input:
text
A, B, A, A, B
Algorithm:
text
for each x:
    if x not in D:
        D[x] = 0

    D[x] = D[x] + 1
Trace:
xDictionary after step
A{A:1}
B{A:1,B:1}
A{A:2,B:1}
A{A:3,B:1}
B{A:3,B:2}
Final:
A:3, B:2\boxed{ A:3,\ B:2 }

62. Table trace example

Table:
NameScore
A60
B90
C75
Algorithm:
text
best = first row

for each remaining row:
    if row.Score > best.Score:
        best = row
Trace:
Start:
text
best = A,60
B:
90>6090>60
so:
text
best = B,90
C:
75>9075>90
false.
Final:
(B,90)\boxed{ (B,90) }
Common mistake: modify the wrong row
When iterating:
text
for each row:
make sure update applies to the current intended record.
A table may contain many similar fields.
Trace both:
  • current row
  • field being changed

Common mistake: confuse row index with ID
Suppose:
IDMarks
10580
20090
ID = 105 does not mean row position 105.
It is a field value.
A row index and an identifier are different concepts.

Common mistake: assume table rows are dictionary keys
A table and a dictionary are different structures.
A table may contain duplicate values in a column.
A dictionary key must uniquely identify an entry.
Only use a column as a key when it is suitable as an identifier.

Common mistake: overwrite instead of accumulate
Suppose total sales per city.
Wrong:
text
total[city] = sale
This keeps only the latest sale.
Correct:
text
total[city] = total[city] + sale
after proper initialization.

Common mistake: aggregate before checking key existence
If:
text
total[city]
has never been initialized, then:
text
total[city] = total[city] + sale
may be invalid.
Initialize first:
text
if city not in total:
    total[city] = 0

Common mistake: one counter for many categories
Suppose you need counts for:
text
A
B
C
A single variable:
text
count
cannot tell you separate category counts unless handled in some other structure.
Dictionary:
text
count[A]
count[B]
count[C]
solves that cleanly.

Common mistake: key-value reversal
Given:
text
name → marks
do not later assume:
text
marks → name
Mappings are directional.
Multiple names may share the same mark, so reverse lookup may not even be unique.

70. Table vs dictionary mental model

text
TABLE
│
├── many rows
├── fixed fields/columns
├── iterate records
└── good for datasets

DICTIONARY
│
├── unique keys
├── key → value
├── direct conceptual lookup
└── good for mappings / counts / aggregates

71. Week 6 pattern library

Frequency count

text
freq[x]++

Sum by group

text
sum[group] += value

Count by group

text
count[group] += 1

Average by group

text
sum[group] / count[group]

Lookup

text
value = D[key]

Update

text
D[key] = new_value

72. Week 5 → Week 6 connection

Week 5:
List=ordered sequence\text{List} = \text{ordered sequence}
Week 6:
Table=structured records\text{Table} = \text{structured records}
and:
Dictionary=key-value mapping\text{Dictionary} = \text{key-value mapping}
So your data structures become richer:
text
single variable
    ↓
list
    ↓
table / dictionary

73. Connection to Statistics

This week is also very close to real data analysis.
Statistics frequently starts with a table:
text
rows = observations
columns = variables
Then computational algorithms:
  • filter rows
  • group categories
  • count frequencies
  • compute averages
  • locate extremes
Dictionaries provide a natural way to implement many of these operations.

74. What you should actually master

By the end of CT Week 6, you should be able to:
  1. Explain a table in terms of rows and columns.
  2. Distinguish records, fields and cells.
  3. Iterate through rows.
  4. Filter rows using field conditions.
  5. Update values in a table.
  6. Find max/min records based on a field.
  7. Explain a dictionary as a key-value mapping.
  8. Distinguish key from value.
  9. Perform conceptual dictionary lookup.
  10. Update an existing dictionary entry.
  11. Handle a missing/new key.
  12. Build a frequency dictionary.
  13. Count items by category.
  14. Sum values by category.
  15. Compute grouped averages using sum/count state.
  16. Understand why dictionary keys should uniquely identify entries.
  17. Trace dictionary state step-by-step.
If these are comfortable, Computational Thinking Week 6 is under control.

Quick Recall & Flashcards

Test your active recall before proceeding to practice problems. Format:
Question :: Answer.
  • Week 6 Diagnostic: In a dictionary / hash map, what is the expected time complexity to look up a value by its key? :: Answer: A — Dictionaries provide O(1) average-time lookup by key via hash-based indexing.
  • Week 6 Diagnostic: Can a dictionary have duplicate keys? :: Answer: B — Dictionary keys are strictly unique. Reassigning to an existing key overwrites the previous value.

Practice & Self-Check

Attempt these diagnostic questions to verify your operational understanding.
1

Question 1

In a dictionary / hash map, what is the expected time complexity to look up a value by its key?
MCQ
3 Unit Assessment
A. O(1)
B. O(N)
C. O(N^2)
D. O(log N)
2

Question 2

Can a dictionary have duplicate keys?
MCQ
3 Unit Assessment
A. Yes, multiple identical keys are allowed with different values
B. No, keys must be unique; assigning to an existing key updates its value
C. Only if keys are integers
D. Yes, up to a maximum of 256 keys

Active Recall Session

Document outline

Keep your place and jump directly to a heading.

Table of contents

No note selected

Open a chapter to see its outline, backlinks, and sources here.