| Tip 42 | Count with defaultdict |
★★2.7, 3.4+ When you count the number of occurrences of a particular item in an iterable (say, a specific character in a string), you use an integer number as a counter. When the iterable consists of heterogeneous items and you know the number of their types ahead of time, you can use a list of counters, especially if the item types map nicely to list indexes. But if the number of types is large or unknown, a dictionary is the best counting tool. Iterate through the iterable, check if you have seen the next item before. If so, increment its counter in the dictionary. If not, create a new dictionary item for the new item in the iterable and increment it, anyway:
| | counter = {} |
| | for item in iterable: |
| | if item ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access