SECTION 10 / 31

Count students from each city

1 min read
Small constructed example: two Chennai records and one Bengaluru record give counts 2 and 1. The lab uses all 30 original students.
Small constructed example: two Chennai records and one Bengaluru record give counts 2 and 1. The lab uses all 30 original students.
REAL COURSE DATA · KEYS, COUNTS AND CONNECTIONS

Count students from each city

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.

Now use CityTown as the key and a student count as the value. Each record increments exactly one city. This is the same create-or-increment pattern as word lengths; only the chosen key changes. You no longer need separate counters named ChennaiCount, MaduraiCount and so on.

cityCount = {}
foreach X in scores {
    city = X.CityTown
    if (not isKey(cityCount,city)) {
        cityCount[city] = 0
    }
    cityCount[city] = cityCount[city] + 1
}

Use consistent labels. “Bengaluru” is the dataset label; the spoken lecture sometimes says Bangalore. A deliberate alias map can combine known alternatives. Do not automatically merge unrelated places just because their names look similar.

Try it yourself

What do city keys represent?

Show explained answer

The distinct CityTown labels observed in the input.

Try it yourself

Why is setting a new city to 0 followed by adding 1 correct?

Show explained answer

The first record becomes 1; later records increment the accumulated value.

Try it yourself

Does reversing the cards change city totals?

Show explained answer

No. It may change intermediate states, but each student still contributes once to the same city.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑