Count repeated tokens with a dictionary
Type one expression at a time and check its delimiters. · 180 words
Tokens are small text pieces, such as words, that an AI experiment can count. A dictionary stores key-value pairs; here, each token is a key and its count is a value. Start with counts = {} and update it with counts[token] = counts.get(token, 0) + 1. The method get(token, 0) returns the current count or zero when the token is new. For notes = 'red blue red green blue red', notes.split() gives ['red', 'blue', 'red', 'green', 'blue', 'red']. The loop then produces {'red': 3, 'blue': 2, 'green': 1}. Repeated-token counts can reveal frequent prompt terms or class imbalance.
For a second experiment, combine tokens from several records. Let documents = [['data', 'model'], ['data', 'test']]. Use counts = {} and run two nested loops: for document in documents: and for token in document:. Inside the inner loop, apply counts[token] = counts.get(token, 0) + 1. The result is {'data': 2, 'model': 1, 'test': 1}. The outer loop selects one document, and the inner loop visits its tokens. A dictionary keeps one count per distinct token without requiring a fixed vocabulary in advance.
Check your recall
Why does counts[token] = counts.get(token, 0) + 1 work the first time a token appears?
Check your answer
The get method returns zero when the token is not already a dictionary key. Adding one therefore creates its first count. On later visits, get returns the existing count so it can be increased.
Sources and credits
Original KeyTouch lesson. Background reading · Python Software Foundation · The Python Tutorial.