Quarry School

Count repeated labels — quick review

In plain words

A tally sheet for a vote has one line for each answer.

Rule

To count labels, start with an empty dictionary. For each label, add 1 to its value when it is already a key, and store it with 1 when it is not. After the loop, each key's value is the number of times that label appeared.

Step

  1. Set counts = {} above the loop.

  2. Loop over the labels with a for loop.

  3. Inside the loop, test if label in counts:.

  4. When it is true, write counts[label] += 1; otherwise write counts[label] = 1, which stores the new key.

  5. After the loop, read a count with counts[label] or print the whole dictionary.

Trap

Writing only counts[vote] += 1 stops at the first vote with a KeyError, because the count is read before anything was stored for that key. The else branch stores the first 1.

Setting counts = {} inside the loop empties the tally on every pass, and only the last vote would be left. Put it above the loop.