Collections
Collections Module
Use Counter when the question is "how many times did each value appear?"
Source
from collections import Counter
counts = Counter("banana")
print(counts.most_common(2))Output
[('a', 3), ('n', 2)]Use defaultdict(list) when each key gathers multiple values and the missing-key case should create an empty list automatically.
Source
from collections import defaultdict
groups = defaultdict(list)
for name, team in [("Ada", "red"), ("Grace", "blue"), ("Lin", "red")]:
groups[team].append(name)
print(dict(groups))Output
{'red': ['Ada', 'Lin'], 'blue': ['Grace']}Use deque for queue operations at both ends, and namedtuple when a tiny immutable record needs names as well as positions.
Source
from collections import deque, namedtuple
queue = deque(["first"])
queue.append("second")
print(queue.popleft())
Point = namedtuple("Point", "x y")
print(Point(2, 3).x)Output
first
2Notes
Countercounts,defaultdictgroups,dequequeues, andnamedtuplenames record fields.- Prefer the built-in containers until a specialized shape makes the code clearer.
- For new structured records with defaults and methods, consider
dataclassesinstead ofnamedtuple.
See also
- related: Dictionaries
- related: Lists
- related: Tuples
- related: Sets
Run the complete example
Expected output
[('a', 3), ('n', 2)]
{'red': ['Ada', 'Lin'], 'blue': ['Grace']}
first
2
Execution time appears here after you run the example.