Unit 7Counting with Counters

A counter is a dictionary-style collection for tallying items in another collection. It is defined in the module collections. You can pass the collection to be tallied to the constructor Counter and then use the function most_common(n) to get a list of n most frequent items and their frequencies (if you don’t provide n, the function will return a list of all items).

 from​ collections ​import​ Counter
 phrase = ​"a man a plan a canal panama"
 cntr = Counter(phrase.split())
 cntr.most_common()
=> [('a', 3), ('canal', 1), ('panama', 1), ('plan', 1), ('man', 1)]

The latter list can be converted to a dictionary for easy look-ups:

 cntrDict = dict(cntr.most_common())
=> {'a': 3, 'canal': 1, 'panama': 1, 'plan': 1, ...

Get Data Science Essentials in Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.