-1

I am new to python I am writing code to count the frequency of numbers in a list However I get KeyError. How to automatically check if value does not exist and return a default value. My code is below

arr = [1,1,2,3,2,1]
freq={}
for i in arr:
   freq[i] += freq[i] + 1

3 Answers3

1

Yes you can leverage the get method of a dictionary. You can simply do

arr=[1,1,2,3,2,1]
freq={}
for i in arr:
    freq[i] = freq.get(i,0)+1

Please Google for basic question like this before asking on stackoverflow

dracarys
  • 1,071
  • 1
  • 15
  • 31
0

You want the dictionary's get method.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

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.

Talon
  • 1,775
  • 1
  • 7
  • 15