7

Possible Duplicate:
How to count the frequency of the elements in a list?

I wish to count the number of elements of same value in a list and return a dict as such:

> a = map(int,[x**0.5 for x in range(20)])
> a
> [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4] 

> number_of_elements_by_value(a)
> {0:1, 1:3, 2:5, 3:7, 4:4}

I guess it is kind of a histogram?

Community
  • 1
  • 1
Theodor
  • 5,536
  • 15
  • 41
  • 55
  • I didn't downvote but it's probably because you could have found the answer to this with a few seconds of searching as it's probably among the most duped question around. – aaronasterling Nov 09 '10 at 10:14
  • The mentioned "duplicate" does not answer this question, since Theodor is asking for a dict as the result, which is exactly what I was just looking for.http://stackoverflow.com/questions/2161752/how-to-count-the-frequency-of-the-elements-in-a-list gives a different output. - Upvoted :-) – Simon Steinberger Oct 08 '12 at 07:40

4 Answers4

8

This is a good way if you don't have collections.Counter available

from collections import defaultdict
d = defaultdict(int)
a = map(int, [x**0.5 for x in range(20)])
for i in a:
    d[i] += 1

print d
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • Thanks, that worked nicely. I should probably update Python like mentioned above, but time is always short ;) – Theodor Nov 09 '10 at 09:53
7

Use a Counter:

>>> from collections import Counter

>>> a = map(int,[x**0.5 for x in range(20)])
>>> a
[0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4] 
>>> c = Counter(a)
>>> c[2]
5
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • Like Mark Byers noted, Counter is only available in Python 2.7+. But I think its time to update my 2.6.6 anyway ;) – Theodor Nov 09 '10 at 09:19
4

Use count to get the count of an element in list and set for unique elements:

>>> l = [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4]
>>> k = [(x, l.count(x)) for x in set(l)]
>>> k
[(0, 1), (1, 3), (2, 5), (3, 7), (4, 4)]
>>> 
>>> 
>>> dict(k)
{0: 1, 1: 3, 2: 5, 3: 7, 4: 4}
>>> 
pyfunc
  • 65,343
  • 15
  • 148
  • 136
0

Before there was Counter, there was groupby:

>>> a = map(int,[x**0.5 for x in range(20)])
>>> from itertools import groupby
>>> a_hist= dict((g[0],len(list(g[1]))) for g in groupby(a))
>>> a_hist
{0: 1, 1: 3, 2: 5, 3: 7, 4: 4}

(For groupby to work for this purpose, the input list a must be in sorted order. In this case, a is already sorted.)

PaulMcG
  • 62,419
  • 16
  • 94
  • 130