Counting and grouping
Learn in depth →Counter counts hashable values; defaultdict creates a missing value when accessed with [].
Counter(iterable); defaultdict(factory)Example
from collections import Counter, defaultdict
print(sorted(Counter("banana").items()))
groups = defaultdict(list)
groups["fruit"].append("pear")
print(dict(groups))Result
[('a', 3), ('b', 1), ('n', 2)]
{'fruit': ['pear']}Watch for: defaultdict.get does not invoke the factory. Counter entries may have zero or negative counts.
Practise this topic →