Reputation: 93
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
Upvotes: 0
Views: 47
Reputation: 398
You could use h.get(i,[0]*4)[3]
. Should do the trick. Although this assumes you won't index higher than 3. If you index higher you can return a longer array of zeros within the get
method.
Upvotes: 1
Reputation: 9504
The problem is that your values in the dictionary are lists.
So for h[i]
defaultdict
might help you if i
doesn't exist but for the inner access, it can't help since there is no defaultlist which will return something if there is an empty list.
The best you can do is:
h = defaultdict(list)
h[1]=['chr1','12','20','1']
h[2]=['chr1','15','20','2']
for i in range(1, 5):
print(h[i][3] if h.get(i) and len(h.get(i))>=4 else 0) # checks also that there is at least 4 elements in the list
Upvotes: 1
Reputation: 2328
Use a try except.
try:
for i in range(1, 5):
print(h[i][3])
except KeyError as e:
print('Key error - %s' % str(e))
print(0)
Upvotes: 1