collections.Counter

suggest change

Counter is a dict sub class that allows you to easily count objects. It has utility methods for working with the frequencies of the objects that you are counting.

import collections
counts = collections.Counter([1,2,3])

the above code creates an object, counts, which has the frequencies of all the elements passed to the constructor. This example has the value Counter({1: 1, 2: 1, 3: 1})

Constructor examples

Letter Counter

>>> collections.Counter('Happy Birthday')
Counter({'a': 2, 'p': 2, 'y': 2, 'i': 1, 'r': 1, 'B': 1, ' ': 1, 'H': 1, 'd': 1, 'h': 1, 't': 1})

Word Counter

>>> collections.Counter('I am Sam Sam I am That Sam-I-am That Sam-I-am! I do not like that Sam-I-am'.split())
Counter({'I': 3, 'Sam': 2, 'Sam-I-am': 2, 'That': 2, 'am': 2, 'do': 1, 'Sam-I-am!': 1, 'that': 1, 'not': 1, 'like': 1})

Recipes

>>> c = collections.Counter({'a': 4, 'b': 2, 'c': -2, 'd': 0})

Get count of individual element

>>> c['a']
4

Set count of individual element

>>> c['c'] = -3
>>> c
Counter({'a': 4, 'b': 2, 'd': 0, 'c': -3})

Get total number of elements in counter (4 + 2 + 0 - 3)

>>> sum(c.itervalues())  # negative numbers are counted!
3

Get elements (only those with positive counter are kept)

>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']

Remove keys with 0 or negative value

>>> c - collections.Counter()
Counter({'a': 4, 'b': 2})

Remove everything

>>> c.clear()
>>> c
Counter()

Add remove individual elements

>>> c.update({'a': 3, 'b':3})
>>> c.update({'a': 2, 'c':2})  # adds to existing, sets if they don't exist
>>> c
Counter({'a': 5, 'b': 3, 'c': 2})
>>> c.subtract({'a': 3, 'b': 3, 'c': 3})  # subtracts (negative values are allowed)
>>> c
Counter({'a': 2, 'b': 0, 'c': -1})

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Collections module:
* collections.Counter

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
32 Collections module
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve