30

I have used Counter to count the number of occurrence of the list items. I have trouble in displaying it nicely. For the below code,

category = Counter(category_list)
print category

the following is the output,

Counter({'a': 8508, 'c': 345, 'w': 60})

I have to display the above result as follows,

a 8508
c 345
w 60

I tried to iterate over the counter object but I'm unsuccessful. Is there a way to print the output of the Counter operation nicely?

vaultah
  • 44,105
  • 12
  • 114
  • 143
  • Do you want the output sorted alphabetically by the key or in descending order based on the value? – DSM Dec 01 '13 at 19:55
  • Sorry, I should have mentioned that in my question but the answers have already covered both sorted and unsorted ways. I wanted to display the result in descending order based upon the values. –  Dec 01 '13 at 21:06

5 Answers5

30

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
Community
  • 1
  • 1
vaultah
  • 44,105
  • 12
  • 114
  • 143
10

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
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
4

If you do not care abut having brackets at the beginning and the end another option is using pprint. It sorts the counter alphabetically for you.

import pprint
from collections import Counter

category = Counter({'a': 8508, 'c': 345, 'w': 60})
pprint.pprint(dict(category),width=1)

Output:

{'a': 8508,
 'c': 345,
 'w': 60}
wirthra
  • 153
  • 1
  • 10
3

This works:

>>> from collections import Counter
>>> counter = Counter({'a': 8508, 'c': 345, 'w': 60})
>>> for key,value in sorted(counter.iteritems()):
...     print key, value
...
a 8508
c 345
w 60
>>>

Here is a reference on sorted and one on dict.iteritems.

1

I was just looking for a nice in-line formatter:

from collections import Counter

c = Counter({'a': 8508, 'c': 345, 'w': 60})
cs = sorted(c.items(), key=lambda n: n[1], reverse=True)
print(", ".join(f"{el[1]}× {el[0]}" for el in cs))

gives

8508× a, 345× c, 60× w

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958