python - Getting frequency counts of items in a list -


this has been asked before can't seem find straight forward solution. have bunch of numbers in list like:

1234 2233 3232 1234 

i need find way print frequency total items in list using script, this:

1234 2 2233 1 3232 1 

can shed light on me?

thank you

from collections import counter l = [1234,2233,3232,1234] c = counter(l) print c 

outputs:

counter({1234: 2, 3232: 1, 2233: 1}) 

explanation:

this utilizes collections.counter. returns dict object (technically, counter subclass of dict). means can like:

print c[1234] 

and result of

2 

another option have, if aren't looking dictionary object, build list of tuples contains value/count pairs.

zip(counter(l).keys(), counter(l).values()) 

this returns this:

[(3232, 1), (2233, 1), (1234, 2)] 

the counter class added in python 2.7. based on error posted answer, seems using 2.6 or older. can either upgrade 2.7, or can utilize backport of counter class.

you use defaultdict , count items:

from collections import defaultdict  l = [1234,2233,3232,1234] d = defaultdict(int)  curr in l:     d[curr] += 1  print d 

d dictionary looks this:

defaultdict(<type 'int'>, {3232: 1, 2233: 1, 1234: 2}) 

you can access same way counter:

d[1234] 

prints

2