I have a dict h
, the keys are int numbers:
from collections import defaultdict
h = defaultdict(dict)
h[1]=['chr1','12','20','1']
h[2]=['chr1','15','20','2']
print(h)
defaultdict(<class 'dict'>, {1: ['chr1', '12', '20', '1'], 2: ['chr1', '15', '20', '2']})
it works:
for i in range(1, 3):
print(h[i][3])
1
2
but it's possible there are keys which were not defined and have no values, in which case, I want h[i][3]
returns value 0
.
e.g. if I run:
for i in range(1, 5):
print(h[i][3])
although I have used from collections import defaultdict
, the result shows:
1
2
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-45-212d01eedb83> in <module>
1 for i in range(1, 5):
----> 2 print(h[i][3])
KeyError: 3
My question is, how could I make h[i][3]
returns 0
when this i
is not defined and then the result should be:
1
2
0
0