Python Reference ยท Standard Library: Data Structures and Functional Tools
The collections module
Reference for Python's collections module: Counter, defaultdict, deque, namedtuple, OrderedDict and ChainMap, when to use each and common pitfalls.
The collections module extends Python's built-in list, dict, set and tuple with specialized containers that solve common problems with less code: counting items, grouping values, fast queues, tuples with named fields and layered lookups.
You rarely need all of them at once. Reach for Counter when you count, defaultdict when you group, deque when you add or remove at both ends, and namedtuple for small read-only records (though dataclasses is often better for anything with behavior). The classes are covered in detail on their own pages; this page is the map.
from collections import Counter print(Counter("mississippi").most_common(2)) # [('i', 4), ('s', 4)]
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.
What is in the module
| Name | What it is | Typical use |
|---|---|---|
Counter |
dict subclass that counts hashable items; missing keys count as 0. |
Word frequencies, tallies, comparing multisets. |
defaultdict |
dict that creates a default value on first access to a missing key. |
Grouping, building lists or sets per key. |
deque |
Double-ended queue with O(1) appends and pops at both ends. | Queues, sliding windows, breadth-first search. |
namedtuple |
Factory for tuple subclasses with named fields. | Lightweight immutable records. |
OrderedDict |
dict with order-sensitive equality and move_to_end(). |
LRU caches, order-dependent comparisons. |
ChainMap |
A view over several mappings searched in order. | Layered settings, scoped variables. |
UserDict, UserList, UserString |
Wrapper classes designed for subclassing. | Custom containers with predictable behavior. |
The abstract base classes (Mapping, Sequence, Iterable and so on) live in collections.abc; the old aliases directly under collections were removed in Python 3.10.
Usage notes
- Import ABCs from
collections.abc.from collections import Mappingfails on modern Python. - Ordinary
dictkeeps insertion order since Python 3.7.OrderedDictremains useful formove_to_end(),popitem(last=False)and equality that considers order. defaultdictcreates keys on lookup. Merely readingd["missing"]inserts the key. Used.get(key)orkey in dwhen you do not want that.dequeindexing in the middle is O(n). It is built for the ends. Use a list for random access.Countervalues can be zero or negative. Arithmetic likec1 - c2drops results that are not positive; usesubtract()to keep them.namedtuplefields are read-only. Use_replace()to get a changed copy. For mutable records or defaults, usedataclassesortyping.NamedTuple.- Pickling and JSON.
Counter,defaultdictandOrderedDictserialize throughdict(...)for JSON;dequeneedslist(...).
Related
dict,list,tuple,setCounter,defaultdict,deque,OrderedDictandChainMap,namedtuple- Lessons: Collections, Data structures