SECTION 06 / 31

Build a marks dictionary and compute an average

1 min read

Create chemMarks={}, then scan each score card. Store chemMarks[X.CardNo]=X.Chemistry. The lecture shows names as keys; the lab uses unique CardNo values so that repeated names would not overwrite another student. The dictionary keeps a computed view without altering the source cards.

REAL COURSE DATA · KEYS, COUNTS AND CONNECTIONS

Build and look up a marks dictionary

Follow the dictionary as its keys and values change. Predict each lookup or update before revealing the next step.

Ready

CURRENT RECORD / VALUE

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Predict the next key, whether it already exists, and the value that will be stored.

Miniature example: values 76 and 74 total 150, so their average is 75. The full dataset calculation below uses 30 students.
Miniature example: values 76 and 74 total 150, so their average is 75. The full dataset calculation below uses 30 students.
REAL COURSE DATA · KEYS, COUNTS AND CONNECTIONS

Compute a subject average from values

Follow the dictionary as its keys and values change. Predict each lookup or update before revealing the next step.

Ready

CURRENT RECORD / VALUE

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Predict the next key, whether it already exists, and the value that will be stored.

chemMarks = {}
while (Table 1 has more rows) {
    Read the first row X in Table 1
    chemMarks[X.CardNo] = X.Chemistry
    Move X to Table 2
}
total = 0
count = 0
foreach k in keys(chemMarks) {
    total = total + chemMarks[k]
    count = count + 1
}
if (count > 0) {
    average = total / count
}

For the original 30 cards, Chemistry totals 2314 and the mean is 2314/30 ≈ 77.1333. Switching the lab field recomputes the values from those same cards. An empty input has no average; report it rather than dividing by zero.

Try it yourself

Should the average add keys 0,1,2,…?

Show explained answer

No. Add the marks stored at those keys.

Try it yourself

Why use a count variable as well as a total?

Show explained answer

The total is divided by the number of student entries processed.

Try it yourself

What does overwriting duplicate name keys do to an average?

Show explained answer

It can remove a student’s earlier mark from the dictionary, making the resulting average differ from the full-record average.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑