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