Counter, most_common, and elements
Counter(iterable=None, **kwds)
Counter.most_common(n=None)
Counter.elements()Count items from an iterable or from keyword counts. most_common(n) returns the n most frequent items; elements() repeats each item according to its count.
Returns: most_common() returns a list of (element, count) pairs. elements() returns an iterator. Counts of zero or less are ignored by elements().
- Accessing a missing key returns 0 and does not insert the key.
- update() adds counts. subtract() subtracts counts and may store zeros or negatives. The - operator keeps only positive results.
from collections import Counter
counts = Counter("abca")
print(counts)
print(counts["z"])
print(counts.most_common(2))
print(list(counts.elements()))
counts.subtract("aa")
print(dict(counts))Expected output
Counter({'a': 2, 'b': 1, 'c': 1})
0
[('a', 2), ('b', 1)]
['a', 'a', 'b', 'c']
{'a': 0, 'b': 1, 'c': 1}