I am new to python I wanna write a code using defaultdict in collections module in which , something like this: defaultdict (lambda:'0') but I want the values of only those undefined keys to 0 for which key is greater than 0 like for eg: I have this dict = {'24' : 3 ,'43' : 6} for dict['80'] it should be 0 but for dict['-5'] it should be 1. Can someone please help
Asked
Active
Viewed 62 times
-1
-
Why are the keys strings if you care about their numerical values? – DeepSpace Aug 19 '19 at 18:44
1 Answers
1
Don't use defaultdict
. Instead, subclass UserDict
from collections import UserDict
class MyDict(UserDict):
def __missing__(self, key):
return 0 if int(key) > 0 else 1
d = MyDict({'24' : 3 ,'43' : 6})
print(d['24'])
print(d['80'])
print(d['-5'])
Outputs
3
0
1

DeepSpace
- 78,697
- 11
- 109
- 154