Python comes with a module called
collections. It holds ready-made tools for storing data, which do some common jobs more neatly than plain dictionaries or lists. In this lesson you'll meet three: Counter, defaultdict and namedtuple. Import each one from collections before you use it, for example from collections import Counter.Counter
Counting how often each item appears in a list usually takes a few lines of manual dictionary work.
Counter does it in one.from collections import Counter
votes = ['cat', 'dog', 'cat', 'owl']
result = Counter(votes)
print(result)You can add two Counters together with
+, which adds up their counts (plain dictionaries can't be added). And .most_common(n) gives the n most common items, each with its count: here, result.most_common(1) gives [('cat', 2)].defaultdict
A normal dictionary raises
KeyError when you read a key that is not there. A defaultdict fills in a missing key for you. You tell it how to make the starting value: defaultdict(list) gives each new key an empty list.from collections import defaultdict
groups = defaultdict(list)
for name in ['Alice', 'Bob', 'Carol']:
groups[name[0].lower()].append(name)
print(dict(groups))The example above prints
{'a': ['Alice'], 'b': ['Bob'], 'c': ['Carol']}. Printed as it is, a defaultdict shows some extra words, so dict() turns it into a plain dictionary first.defaultdict(int) is common for adding up totals, because int() gives 0. Notice there are no brackets after list or int: you hand over the function itself, and the defaultdict calls it each time it needs a starting value. Any function you can call with nothing in its brackets will do.namedtuple
A plain tuple like
(1, 'Alice') is fine for data, but you cannot tell which position means what. A namedtuple gives fields names while keeping the lightweight, immutable nature of a regular tuple.from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 7)
print(p.x + p.y)A named tuple is still a tuple, so
p[0] and x, y = p work too. Like any tuple, it can't be changed once it's made. So, if what it holds can't be changed either, it can be a dictionary key, or go in a set. If you need a record you can change, with default values and methods, use a dataclass instead.