0

I am looking for a one line, efficient way, given a list, to output a dictionary with keys as the distinct values in the list, and values of the dictionary to be the count of that key in the list.

For example,

a = [1,1,1,2,2,3,]      ##input
b = {1: 3, 2: 2, 3: 1}  ##output

I've found that {i: a.count(i) for i in a} works fine, but it will do excessive computations, such as in an input list a=[1,1,1], it will overwrite the key [1] with the value [3] 3 times.

I could also do something more manual like below, but I am looking for something more elegant and simple.

b = {}
for i in a:
    if i in b:
        b[i] += 1
    else:
        b[a] = 1
cacti5
  • 2,006
  • 2
  • 25
  • 33
  • 1
    You can wrap your list `a` in a set. `b = {i: a.count(i) for i in set(a)}`. No modules needed – cwahls Feb 09 '17 at 04:07

1 Answers1

3

Use collections.Counter:

>>> from collections import Counter
>>> a = [1,1,1,2,2,3,]
>>> b = Counter(a)
>>> b
Counter({1: 3, 2: 2, 3: 1})

Note, Counter is a subclass of dict:

>>> isinstance(b, dict)
True
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • If you see a question that's been answered on the site before, you can flag or vote to close it as a duplicate (especially when Googling the question's title would've been more than sufficient research). – TigerhawkT3 Feb 09 '17 at 04:18