Formatting output of Counter

print calls __str__ method of Counter class, so you need to override that in order to get that output for print operation.

from collections import Counter
class MyCounter(Counter):
    def __str__(self):
        return "\n".join('{} {}'.format(k, v) for k, v in self.items())

Demo:

>>> c = MyCounter({'a': 8508, 'c': 345, 'w': 60})
>>> print c
a 8508
c 345
w 60

Counter is essentially a dictionary, thus it has keys and corresponding values - just like the ordinary dictionary. From the documentation:

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

You can use this code:

>>> category = Counter({'a': 8508, 'c': 345, 'w': 60})
>>> category.keys() 
dict_keys(['a', 'c', 'w'])
>>> for key, value in category.items():
...     print(key, value)
... 
a 8508
c 345
w 60

However, you shouldn't rely on the order of keys in dictionaries.

Counter.most_common is very useful. Citing the documentation I linked:

Return a list of the n most common elements and their counts from the most common to the least. If n is not specified, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily.

(emphasis added)

>>> category.most_common() 
[('a', 8508), ('c', 345), ('w', 60)]
>>> for value, count in category.most_common():
...     print(value, count)
...
a 8508
c 345
w 60

Tags:

Python