The Dictionary get() Method
A dictionary key represents a unique character. Its value represents how many times that character has been counted so far.
A Counting Decision
Suppose you want to know how many times each letter appears in the word brontosaurus. A dictionary can store each unique character as a key and its count as the associated value. The key decision is the same for every character: is this the first time the character has appeared, or is it already in the dictionary? A new character starts with a count of 1. An existing character has its count increased by 1.
What do you think happens?
When the first character b is processed, what should its count be in the dictionary?
Reveal answer
1
The first occurrence of a character creates a new dictionary entry with a count of 1.
The First Characters
Process the word brontosaurus from left to right. The first character is b, so the dictionary begins with b mapped to 1. The next character is r, which has not appeared before, so r is added with a count of 1. The same initialization happens for o and n. Each new character creates a new key-value entry rather than changing an existing entry.
A dictionary key represents a unique character. Its value represents how many times that character has been counted so far.
The Conditional Pattern
The explicit approach checks whether the current character c is already a key in dictionary d. If c is not in d, the program assigns d[c] = 1 because this is the first occurrence. If c is already in d, the program increases d[c] by 1 because another occurrence has been found.
counts = {}
for c in "brontosaurus":
if c not in counts:
counts[c] = 1
else:
counts[c] += 1- 1The empty dictionary has no character keys yet.
- 2For each character c, the membership check determines which branch to use.
- 3The initialization branch records the first occurrence.
- 4The increment branch records every later occurrence.
- counts starts as an empty dictionary.
- The loop processes each character in the word.
- A missing character receives its first count of 1.
- An existing character has its count increased by 1.
Processing the Repeated o
Trace what happens when the character o is encountered after the dictionary already contains b, r, o, n, and t.
- 1Inspect the key
The character o is already a key in the dictionary, so this is not an initialization case.
- 2Read the current value
The dictionary currently stores the count associated with o.
- 3Increment the value
Add 1 to the current count and store the updated value back under the key o.
The count for o increases by 1, while the other character counts remain unchanged.
How get() Removes the Branch
The dictionary get() method retrieves the value associated with a key. It can also receive a default value to use when the key is missing. In character counting, d.get(c, 0) returns the current count when c already exists. When c is missing, it returns 0 instead. Adding 1 and assigning the result to d[c] handles both cases in one expression.
The default value of 0 is the key to the shorter approach. A new character behaves as if its previous count were 0, so adding 1 creates the correct first count. An existing character contributes its stored count, so adding 1 produces the next count. The expression therefore replaces the separate initialization and increment branches without changing the result.
get() reads a value with a fallback; it does not by itself create a dictionary entry. The assignment to d[c] stores the new count.
Two Equivalent Implementations
The conditional and get()-based approaches use different syntax but follow the same counting process. Both iterate through the string, examine one character at a time, and update the dictionary. For a new character, the conditional version stores 1 while the get() version computes 0 + 1. For an existing character, the conditional version adds 1 to the stored count while get() retrieves that same count and adds 1.
| Approach | How a missing character is handled | How an existing character is handled | Main characteristic |
|---|---|---|---|
| Conditional | Assign 1 | Add 1 to the stored count | More explicit |
| get() | Use default 0, then add 1 | Retrieve the stored count, then add 1 | More concise |
Both approaches iterate through the string and produce identical character counts.
Practice the State Changes
Trace the dictionary while processing the characters in the string "level". Write the dictionary after each character is processed using the get()-based counting pattern.
Hints
- Start with an empty dictionary.
- The first l uses the default value 0 and becomes 1.
- When a character appears again, retrieve its stored count and add 1.
Checking the Repeated Characters
Determine the final character counts for the string "level".
- 1Read l, e, v
Each character is new when first encountered, so each receives a count of 1.
- 2Read the second e
e is already present with a count of 1, so its count becomes 2.
- 3Read the second l
l is already present with a count of 1, so its count becomes 2.
The final dictionary is {l: 2, e: 2, v: 1}.
Common mistake Initializing every character to 1 without checking whether it has already been counted.
What it looks likeReplacing an existing count with 1 each time the character appears.
Why it failsRepeated characters would never accumulate their occurrences.
Do this insteadUse the conditional approach to distinguish new and existing keys, or use d.get(c, 0) + 1.
Common mistake Using get(c) without a default value for a character that may be missing.
What it looks likeTrying to add 1 to the result of d.get(c) when c is not yet a key.
Why it failsThe counting pattern requires a numeric fallback of 0 for a missing character.
Do this insteadUse d.get(c, 0) so a new character contributes 0 + 1.Common mistake Calling get() but not assigning the updated count back to the dictionary.
What it looks likeWriting d.get(c, 0) + 1 without storing that result in d[c].
Why it failsThe retrieved or calculated value is not recorded as the character's new count.
Do this insteadAssign the result with d[c] = d.get(c, 0) + 1.
The Counting Pattern
- 1A dictionary can map each unique character in a string to the number of times it appears.
- 2The conditional approach initializes a missing character to 1 and increments an existing character by 1.
- 3The expression
d.get(c, 0)+ 1 treats a missing character as if its previous count were 0. - 4The conditional and
get()-based approaches produce identical character counts. - 5Understanding both forms helps you read explicit beginner-friendly code and concise practical code.
Key Takeaways
- Character counting stores unique characters as dictionary keys and their counts as values.
- A new character must be initialized with a count of 1.
- An existing character must have its count increased by 1.
- The
get()method uses 0 as a default for missing characters, allowing both cases to be written as d[c] =d.get(c, 0)+ 1. - Conditional and
get()-based counting are equivalent approaches.