0

It is very strange, even though I can see that the key exist it still gives me an error:

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
Oren
  • 4,711
  • 4
  • 37
  • 63
  • 1
    You are relying on floating point numbers to print exact representations. They do not. Floating point numbers as dictionary keys are fraught with difficulty, especially if you are generating floats. – juanpa.arrivillaga Sep 22 '18 at 01:22

1 Answers1

1

You need to round the float values:

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])

Output

True
True
0

See this.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76