Dictionaries: Mapping Keys to Values
The get() method safely retrieves dictionary values, returning a default if the key is missing.
A Safer Dictionary Lookup
A dictionary connects keys with values. When a program needs the value associated with a key, the get() method provides a safe lookup pattern: it retrieves the dictionary value when the key is present and supplies a default value when the key is missing. This makes get() especially useful when a program is counting items and cannot assume that every key has already been added.
Existing and Missing Keys
The get() method has two important cases. If the requested key exists, get() retrieves the value associated with that key. If the key is missing, get() returns the default supplied as its second argument. In the counting idiom, that default is 0 because a key that has not been counted yet has a current count of zero for the purpose of the calculation.
7
0The Default-Value Path
The second argument to get() is the fallback value. The lookup first considers the requested key. An existing key leads to its associated dictionary value. A missing key leads to the supplied default instead. This is why get() is safer than relying on bracket notation when a key may not exist: the lookup has an explicit result for the missing-key case.
Choose a default that represents the starting value your operation needs. For frequency counting, use 0 because the first occurrence should increase a missing count from zero to one.
From Conditional Logic to Counting
A counting loop must handle two situations: the item may already have a count, or it may be appearing for the first time. An explicit if-statement can separate those cases. The get() idiom combines them by retrieving the current count when available, using 0 otherwise, adding 1, and assigning the result back to the dictionary.
items = ["cat", "dog", "cat", "bird"] counts = {} for item in items: counts[item] = counts.get(item, 0) + 1 print(counts)
Building a Frequency Histogram
A histogram records how often each item occurs. A dictionary is a natural structure for this task: each distinct item serves as a key, and its associated value is the number of occurrences counted so far. The get() idiom makes every loop iteration follow the same update rule, whether the item has appeared before or is appearing for the first time.
Counting Letter Occurrences
Build a frequency count for the letters in the sequence ["a", "b", "a", "c", "b", "a"].
Initialize: Start with an empty dictionary named counts.
Process a: The key a is missing, so get("a", 0) returns 0. Add 1 and store a count of 1.
Process b: The key b is missing, so get("b", 0) returns 0. Add 1 and store a count of 1.
Process a again: The key a exists with a count of 1. Add 1 and store a count of 2.
Process c: The key c is missing, so its count becomes 1.
Process b again: The key b exists with a count of 1. Add 1 and store a count of 2.
Process a a third time: The key a exists with a count of 2. Add 1 and store a count of 3.
The resulting histogram is {"a": 3, "b": 2, "c": 1}.
{"a": 3, "b": 2, "c": 1}Mistakes Beginners Make
Using a lookup pattern that does not provide a missing-key fallback.
A counting loop must handle items that have not appeared before.
Fix:
Use counts.get(item, 0) so a missing item begins with a count of zero.Forgetting to add one before assigning the result.
The expression retrieves the current count or default but does not record the new occurrence.
Fix:
Use counts[item] = counts.get(item, 0) + 1.Treating the default as the final count.
For frequency counting, the current occurrence still needs to be added.
Fix:
Use the default as the starting count, then add 1.Using get() without considering what the default should mean.
The default represents the starting value for a missing key.
Fix:
For occurrence counts, use 0 as the default.
Practice the Refactoring
Rewrite this counting loop using the get() idiom. Then state what the final dictionary contains. items = ["x", "y", "x", "x", "y"] counts = {} for item in items: if item in counts: counts[item] = counts[item] + 1 else: counts[item] = 1
Hints
- Keep counts[item] on the left side of the assignment.
- Use counts.get(item, 0) to retrieve the existing count or starting value.
- Add 1 before assigning the result.
What do you think happens?
Before checking the answer, predict the final value of counts after processing ["x", "y", "x", "x", "y"] with counts[item] = counts.get(item, 0) + 1.
Reveal answer
Answer: {"x": 3, "y": 2}
The sequence contains three occurrences of x and two occurrences of y. Each iteration retrieves the current count or uses zero, then adds one.
Working Rule
- get() retrieves the value for an existing dictionary key.
- When the key is missing, get() returns the supplied default value.
- The expression d[c] = d.get(c, 0) + 1 is a concise counting idiom.
- A dictionary histogram maps each distinct item to its frequency.
- Use get() when a key may not exist and the operation needs a defined fallback.
Key Takeaways
- The get() method safely retrieves a dictionary value or returns a chosen default when the key is missing.
- For counting, get(c, 0) supplies the starting count for a new key.
- The idiom d[c] = d.get(c, 0) + 1 replaces verbose conditional counting logic.
- Repeatedly applying this pattern builds histograms and frequency counts.