Dictionary patterns
Accumulate values by key and iterate over key-value pairs.
On this page
The concept
Counting is a common dictionary pattern. counts.get(word, 0) + 1 starts an unseen word at zero and increases the count. It avoids assuming the key already exists. items() supplies key-value pairs that can be unpacked directly in a for loop.
update merges fields into an existing dictionary. setdefault stores a default only if the key is absent. pop removes a key and returns its value; its optional default defines the missing-key policy. These operations should be chosen for clarity, not chained into a hard-to-read expression.
Worked example
stock = {"apple": 4, "banana": 2}
stock.update({"apple": 6, "orange": 3})
stock.setdefault("pear", 0)
for product, quantity in stock.items():
print(product, quantity)
removed = stock.pop("pear", 0)
print("Removed:", removed)
words = ["python", "code", "python"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)Trace the result
- The stock update replaces apple and adds orange.
- The pear entry is created with zero and later removed.
- The word loop builds a fresh counts dictionary; python finishes with count 2.
apple 6
banana 2
orange 3
pear 0
Removed: 0
{'python': 2, 'code': 1}Line-by-line walkthrough
Line 1: stock = {"apple": 4, "banana": 2}
Evaluate {'apple': 4, 'banana': 2}, then bind or update stock with the result. The chosen collection determines how later access, membership, and mutation behave. Assignment itself does not imply a deep copy.
Line 2: stock.update({"apple": 6, "orange": 3})
Call stock.update to merge fields into the existing mapping. This call may have an effect even when its return value is not assigned.
Line 3: stock.setdefault("pear", 0)
Call stock.setdefault with the displayed arguments. This call may have an effect even when its return value is not assigned.
Lines 4–5: for product, quantity in stock.items():
Obtain each item from stock.items() and bind it to (product, quantity) before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.
Line 5: print(product, quantity)
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Line 6: removed = stock.pop("pear", 0)
Evaluate stock.pop('pear', 0), then bind or update removed with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.
Line 7: print("Removed:", removed)
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Line 8: words = ["python", "code", "python"]
Evaluate ['python', 'code', 'python'], then bind or update words with the result. The chosen collection determines how later access, membership, and mutation behave. Assignment itself does not imply a deep copy.
Line 9: counts = {}
Evaluate {}, then bind or update counts with the result. The chosen collection determines how later access, membership, and mutation behave. Assignment itself does not imply a deep copy.
Lines 10–11: for word in words:
Obtain each item from words and bind it to word before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.
Line 11: counts[word] = counts.get(word, 0) + 1
Evaluate counts.get(word, 0) + 1, then bind or update counts[word] with the result. Assignment itself does not imply a deep copy.
Line 12: print(counts)
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Common mistake
Do not add or remove dictionary keys while iterating over the dictionary itself. Select keys first or iterate over a copied list of keys.