即使存在密钥,也会发生KeyError

时间:2018-09-22 00:58:31

标签: python numpy dictionary

这很奇怪,即使我看到密钥存在,它仍然给我一个错误:

import numpy as np
stim_end_time = 4000
bin_times = np.arange(0,stim_end_time+100,0.025)
time_to_fr = {bin_times[i]:0 for i in range(len(bin_times[:-1]))}
print(0.075 in time_to_fr)
print(0.075 in time_to_fr.keys())
print(np.sort(time_to_fr.keys())[:10])
time_to_fr[0.075]

False
False
[0.    0.025 0.05  0.075 0.1   0.125 0.15  0.175 0.2   0.225]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-d4c6a4c93742> in <module>()
      6 print(0.075 in time_to_fr.keys())
      7 print(np.sort(time_to_fr.keys())[:10])
----> 8 time_to_fr[0.075]

KeyError: 0.075

1 个答案:

答案 0 :(得分:1)

您需要舍入浮点值:

import numpy as np

stim_end_time = 4000
bin_times = np.arange(0, stim_end_time + 100, 0.025)
time_to_fr = {np.round(bin_times[i], 4) : 0 for i in range(len(bin_times[:-1]))}
print(0.0750 in time_to_fr)
print(0.0750 in time_to_fr.keys())
print(time_to_fr[0.0750])

输出

True
True
0

请参见this