In the python library, there is a defaultdict
which can help you here
Documentation for the defaultdict
import collections
arr = [1, 1, 2, 3, 2, 1]
freq = collections.defaultdict(int) # The `int` makes the default value 0
for i in arr:
freq[i] += freq[i] + 1
When you try to access a defaultdict
with a key that is not yet present, it executes the function that you supply when creating it - Calling int()
without any arguments gives you a zero.
Sidenote: It seems that you want to count the occurances of numbers in your array, then you'd want to change your updating to
for i in arr:
freq[i] += 1
Also, the Counter object might be of interest for you.