0
//in C++
unordered_map<int,int>m;
for (i = 0; i < n; ++i) {
          m[arr[i]]++;
}

#in python
my_dict = {}
for i in range(len(arr)):
       my_dict[arr[i]] += 1 #This gives key error

I am sure that the default value is set to zero in C++, so it works. How to go about it in Python?

Costantino Grana
  • 3,132
  • 1
  • 15
  • 35
  • related/dupe: https://stackoverflow.com/questions/2161752/how-to-count-the-frequency-of-the-elements-in-an-unordered-list – NathanOliver Jun 08 '21 at 02:01

3 Answers3

2

In python you could use defaultdict.

from collections import defaultdict

arr = [1,2,3]

my_dict = defaultdict(int)
for i in range(len(arr)):
    my_dict[arr[i]]+=1
Loocid
  • 6,112
  • 1
  • 24
  • 42
1

As @Loocid suggested defaultdict is the way to go. The other option is to use get() with a default value:

my_dict = {}
for i in range(len(arr)):
    my_dict[arr[i]] = my_dict.get(arr[i], 0) + 1

or avoid the indexing with

my_dict = {}
for a in arr:
    my_dict[a] = my_dict.get(a, 0) + 1

Written with a smartphone and unchecked

Costantino Grana
  • 3,132
  • 1
  • 15
  • 35
0

The alternative is defaultdict. You can use a function to set a default value.

Example :

from collections import defaultdict

def not_inside_dict():
    return 0;

d = defaultdict(not_inside_dict)

d[1] = 7
d[2] = 9

for i in range(1,4):
    print(d[i])

Result:

7
9
0

You can also declare like this :

from collections import defaultdict

d = defaultdict(int)

d[1] = 7
d[2] = 9

for i in range(1,4):
    print(d[i])

And it will still return 0 when encountering elements not inside the dict.

silverfox
  • 1,568
  • 10
  • 27