Python 3D Academyবাংলা

Counting and grouping with a dict

🌍 In real life. At the end of the day a shopkeeper empties the cash box onto the counter and sorts the coins into piles: all the 1-taka coins together, all the 2s, all the 5s. Each coin is picked up once and dropped on its pile; then counting a pile is easy. Nobody compares every coin with every other coin.

A dict does this sorting for you: the key is the pile's label, the value is the pile (or just how big it is).

The idea in one sentence: walk the items once and use a dict whose key says which group an item belongs to; the value is the count (counting) or the list of items (grouping).

Its words:

  • counting: keeping, for each key, how many items had it
  • grouping: keeping, for each key, the list of items that had it
  • anagrams: words made of the same letters, like "listen" and "silent"; sorting their letters gives them the same key
  • setdefault: a dict method that adds a key with a starting value only if the key is missing, then returns its value

How it works, step by step:

  1. start with an empty dict
  2. for each item, work out its key (the coin's value, a word's first letter, a word's sorted letters)
  3. counting: counts[key] = counts.get(key, 0) + 1; grouping: groups.setdefault(key, []).append(item)
  4. each step is one O(1) dict lookup, so the whole job is one pass: O(n)

Watch the coins go onto their piles. Each one is a single lookup, however many piles there are:

Grouping anagrams. Words with the same letters are anagrams: "listen", "silent", "enlist". Sorting a word's letters gives every anagram the same key: "".join(sorted("silent")) is "eilnst". So one pass with a dict of lists groups them.

Why it is correct. Two words are anagrams exactly when their sorted letters are equal, so they get the same key and the same list, and words that aren't anagrams get different keys.

What it costs, worked out. Checking every word against every other is n(n−1)/2 anagram checks, and each check sorts two words. The dict sorts each word once and does one lookup:

  • 100 words: 4,950 pair checks against 100 sorts and 100 lookups
  • 10,000 words: about 50 million pair checks against 10,000 sorts and 10,000 lookups

For short words a sort is a handful of steps, so the dict grows like O(n) and the pairs like O(n²).

The built-in way. collections.Counter(items) counts in one line, and defaultdict(list) groups without setdefault (Chapter 30).

words = ["listen", "tea", "silent", "eat", "enlist", "ate", "cat"]
groups = {}
for word in words:
    key = "".join(sorted(word))
    groups.setdefault(key, []).append(word)

for key, group in groups.items():
    print(key, group)
Keys keep the order they were first added, so the groups come out in the order their first word appeared.

Mistakes and edge cases. counts[key] += 1 on a new key raises KeyError: start it with get(key, 0) or use a Counter. A list can't be a key, so sorted(word) (a list) must be turned into a string or a tuple first. And case matters: "Tea" and "eat" only group together if you lower-case them first.

Quiz

  1. What does this print?

    counts = {}
    for coin in [5, 1, 2, 5, 5, 1]:
        counts[coin] = counts.get(coin, 0) + 1
    print(counts)
  2. What does this print?

    print("".join(sorted("tea")), "".join(sorted("eat")))
  3. Counting the words in a list of n words with a dict is…

    • O(n): one pass, one O(1) lookup per word
    • O(n²): every word is compared with every other
    • O(log n): the dict halves the list
  4. Which line raises a KeyError?

    votes = ["Mina", "Rafi", "Mina"]
    counts = {}
    for name in votes:
        counts[name] += 1
    print(counts)
  5. Why is "".join(sorted(word)) used as the key, not sorted(word)?

    • sorted gives a list, and a list can't be a dict key
    • join makes it faster to sort
    • It removes repeated letters

Coding tasks

  1. Write count_chars(text) without Counter: a dict from each character to how many times it appears, in the order characters first appear.

  2. Write group_anagrams(words): a list of groups, each a list of words with the same letters. Groups come in the order their first word appears, and words keep their order inside a group.