🎓 A1Learner
🔍
0 of 52 lessons completed

Python Counting With Dictionaries

Counting with a dict stores each item beside its count. The dict grows one new key at a time as new items appear.

Count one word

get() gives 0 for a new word. The assignment then stores a count of 1.

counts = {}
word = "ada"
counts[word] = counts.get(word, 0) + 1
print(counts)

Count a short list

The loop counts each colour in turn. Red appears three times, and blue appears twice.

words = ["red", "blue", "red", "red", "blue"]
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)

A missing key gives zero

get("red", 0) gives the stored count of 3. get("pink", 0) gives 0 for a missing key.

counts = {"red": 3, "blue": 2}
print(counts.get("red", 0))
print(counts.get("pink", 0))

Example

votes = ["ada", "bob", "ada", "cy", "bob", "ada", "dee", "ada"]
counts = {}
for name in votes:
    counts[name] = counts.get(name, 0) + 1
print(counts)
print("Ada:", counts["ada"])
print("Total votes:", len(votes))
print("Names:", len(counts))

Key points

  • Count: a number stored beside an item in a dict
  • Use counts[item] = counts.get(item, 0) + 1 to count one more
  • Use get(item, 0) to fetch the count so far, or 0 for a new item
  • A missing key with get() gives the 0 from the call, not an error
  • Use counts[item] on its own only when the key is already there
  • Loop over the list once, since each item updates its own count
  • The keys of the counts dict are the items that appeared.

In this example, the list holds eight votes for four names. The loop counts each vote with get(). Ada holds four votes, Bob holds two, and Cy and Dee hold one each. The total of 8 proves every vote was counted. The count of 4 names proves each name got one key.

Note

get() leaves the dict unchanged, so the assignment after it stores the new count.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does counts.get("pink", 0) give when "pink" is missing?