简体   繁体   中英

What is the alternative of unorderd_map in python? We know that default value in key: value is zero in c++

//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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM