Python Reference ยท Standard Library: Data Structures and Functional Tools
collections.Counter
Reference for Python collections.Counter: count hashable items, most_common(), arithmetic between counters, subtract(), total() and the zero-count pitfalls.
collections.Counter is a dict subclass built for counting. Keys are the things you count, values are their counts. Give it any iterable and it tallies the items; give it a mapping and it copies the counts.
Unlike a plain dict, looking up a missing key returns 0 instead of raising KeyError, and the class adds helpers such as most_common(), elements() and arithmetic between counters.
from collections import Counter votes = Counter(["red", "blue", "red"]) print(votes["red"]) # 2 print(votes["green"]) # 0
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
Counter()
Counter(iterable)
Counter(mapping)
Counter(**kwargs)
| Method | Description |
|---|---|
most_common(n=None) |
List of (item, count) pairs, highest count first. Ties keep first-seen order. With n, only the top n. |
elements() |
Iterator that repeats each item as many times as its count. Items with a count below one are skipped. |
update(iterable_or_mapping) |
Adds counts (it does not replace them, unlike dict.update). |
subtract(iterable_or_mapping) |
Subtracts counts and keeps zero and negative results. |
total() |
Sum of all counts (Python 3.10+). |
copy() |
Shallow copy. |
Return value: the constructor returns a new Counter. most_common() returns a list, elements() an iterator, total() an int.
Raises: TypeError if an argument to the constructor or update() is not an iterable or mapping, or if you add an unhashable item.
Usage notes
- Missing keys return 0 but are not inserted. Reading
counts["dog"]does not adddog;"dog" in countsstaysFalse. +and-drop non-positive results.a - bkeeps only positive counts. Usesubtract()when you need negative numbers, or+on a single counter (+c) to strip zero and negative entries.&and|take the minimum and maximum of each count; they also discard non-positive results.- Values can be any number when you assign them directly, but
most_common()andelements()assume integers. Useupdate()/subtract()for normal counting. update()adds.c.update({"a": 2})incrementsaby two;dict.updatewould replace the value.- Counting is by equality and hash. Items must be hashable, so you cannot count lists; convert them to tuples first.
most_common()sorts the whole counter when called withoutn. For the top few items of a very large counter it uses a heap, so passn.- Insertion order is kept (it is a dict), which is why ties in
most_common()appear in first-seen order. - Prefer
Counterto a hand-written loop overd[key] = d.get(key, 0) + 1; it is shorter and implemented in C for iterables.
Related
collectionsmodule,defaultdict,dict.get()sorted(),max()- Lessons: Collections, Dictionaries