Python 3D Academyবাংলা

Counting with a dictionary

🌍 In real life. On election day in a school, someone counts votes with tally marks: a new name gets its own line with one mark, and every vote for a name already on the sheet adds one more mark next to it. At the end, the sheet holds every name with its count.

A dictionary is that tally sheet: names as keys, counts as values.

The idea in one sentence: to count things, start with an empty dictionary and, for each item, do counts[x] = counts.get(x, 0) + 1.

Its words:

  • tally: a running count for each different item
  • counts.get(x, 0): the count so far, or 0 for an item met for the first time
  • anagrams: two words with the same letters, mixed up; their tallies are equal

Step by step, for the items a, b, a:

  1. 'a' is new: get('a', 0) is 0, so counts['a'] becomes 1.
  2. 'b' is new: counts['b'] becomes 1.
  3. 'a' again: get('a', 0) is 1, so counts['a'] becomes 2.
counts = {}
for ch in "banana":
    counts[ch] = counts.get(ch, 0) + 1
print(counts)

Once you have the counts, finding the most common item is the "keep the best so far" loop from Lesson 11.3:

counts = {}
for word in input("Words: ").split():
    counts[word] = counts.get(word, 0) + 1
best = ""
most = 0
for word, n in counts.items():
    if n > most:
        most = n
        best = word
print(best, most)

Two dictionaries are equal when they hold the same pairs, in any order. So two words are anagrams (the same letters, mixed up) when their letter counts are equal:

first = {}
for ch in "listen":
    first[ch] = first.get(ch, 0) + 1
second = {}
for ch in "silent":
    second[ch] = second.get(ch, 0) + 1
print(first == second)

What it costs. Counting n items is one pass with n quick dictionary updates. Compare the slow way: for each different item, list.count(x) walks the whole list again, which for many different items means walking it many times.

Mistakes and edge cases.

  • counts[x] += 1 on a new item. It gives a KeyError: there's no old count to add to. That's what get(x, 0) is for.
  • Starting counts inside the loop. counts = {} inside the loop forgets everything each lap.
  • Capital letters and spaces. "Dog" and "dog" are counted separately, and so is the space in "a b". Clean with .lower() or skip spaces first.
  • The best-so-far starting at 0. Counts are at least 1, so most = 0 is safe here, unlike with temperatures.

Quiz

  1. What does this print?

    counts = {}
    for x in ["a", "b", "a"]:
        counts[x] = counts.get(x, 0) + 1
    print(counts)
  2. What does this print?

    counts = {}
    for ch in "aab":
        counts[ch] = counts.get(ch, 0) + 1
    print(counts["a"])
  3. Why write counts.get(x, 0) instead of counts[x]?

    • The first time, x isn't a key yet, and counts[x] would give a KeyError
    • get() is faster
    • counts[x] can only read strings
  4. What does this print?

    print({"a": 1, "b": 2} == {"b": 2, "a": 1})
  5. Which line has a mistake?

    counts = {}
    for ch in "hi":
        counts[ch] = counts[ch] + 1
    print(counts)

Coding tasks

  1. Ask for a word. Print a dictionary that counts each of its letters, in the order the letters first appear.

  2. Ask for whole numbers on one line. A good pair is two places that hold the same number. Print how many good pairs there are. (A number that appears n times makes n * (n - 1) // 2 pairs.)

  3. Ask for two words, one per line. Print True if they are anagrams (the same letters, the same number of times), otherwise False.