1

Is there a shorter version of the current code for counting the occurrences if an element in an array and store it in a dictionary?

a = [1,2,2,3,4,5,2,2,1]
dic = {}
for x in a:
    if x in dic:
        dic[x] = dic[x] + 1
    else:
        dic[x] = 1

print dic
M.M
  • 1,343
  • 7
  • 20
  • 49

2 Answers2

2

You can use collections.Counter():

from collections import Counter

a = [1, 2, 2, 3, 4, 5, 2, 2, 1]
dic = Counter(a)

From the docs:

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
2

Yes

You can use dictionary.get(key, default) to get a value of a key, and if the key doesn't exist it gives the default argument.

a = [1,2,2,3,4,5,2,2,1]
dic = {}

for n in a:
    dic[n] = dic.get(n, 0) + 1
Ender Look
  • 2,303
  • 2
  • 17
  • 41