Assigning float as a dictionary key changes its precision (Python)
<p>I have a list of floats (actually it's a pandas Series object, if it changes anything) which looks like this:</p>

<pre><code>mySeries:

...
22      16.0
23      14.0
24      12.0
25      10.0
26       3.1
...
</code></pre>

<p>(So elements of this Series are on the right, indices on the left.) Then I'm trying to assign the elements from this Series as keys in a dictionary, and indices as values, like this:</p>

<pre><code>{ mySeries[i]: i for i in mySeries.index }
</code></pre>

<p>and I'm getting pretty much what I wanted, except that...</p>

<pre><code>{ 6400.0: 0, 66.0: 13, 3.1000000000000001: 23, 133.0: 10, ... }
</code></pre>

<p>Why has <code>3.1</code> suddenly changed into <code>3.1000000000000001</code>? I guess this has something to do with the way the floating point numbers are represented (?) but why does it happen <em>now</em> and how do I avoid/fix it?</p>

<p><strong>EDIT:</strong> Please feel free to suggest a better title for this question if it's inaccurate.</p>

<p><strong>EDIT2:</strong> Ok, so it seems that it's the exact same number, just <em>printed</em> differently. Still, if I assign <code>mySeries[26]</code> as a dictionary key and then I try to run:</p>

<pre><code>myDict[mySeries[26]]
</code></pre>

<p>I get <code>KeyError</code>. What's the best way to avoid it?</p>

<p>The value is already that way in the Series:</p>

<pre><code>&gt;&gt;&gt; x = pd.Series([16,14,12,10,3.1])
&gt;&gt;&gt; x
0    16.0
1    14.0
2    12.0
3    10.0
4     3.1
dtype: float64
&gt;&gt;&gt; x.iloc[4]
3.1000000000000001
</code></pre>

<p>This has to do with floating point precision:</p>

<pre><code>&gt;&gt;&gt; np.float64(3.1)
3.1000000000000001
</code></pre>

<p>See <a href="http://stackoverflow.com/questions/5160339/floating-point-precision-in-python-array">Floating point precision in Python array</a> for more information about this.</p>

<p>Concerning the <code>KeyError</code> in your edit, I was not able to reproduce. See the below:</p>

<pre><code>&gt;&gt;&gt; d = {x[i]:i for i in x.index}
&gt;&gt;&gt; d
{16.0: 0, 10.0: 3, 12.0: 2, 14.0: 1, 3.1000000000000001: 4}
&gt;&gt;&gt; x[4]
3.1000000000000001
&gt;&gt;&gt; d[x[4]]
4
</code></pre>

<p>My suspicion is that the <code>KeyError</code> is coming from the <code>Series</code>: what is <code>mySeries[26]</code> returning?</p>

python pandas dictionary floating-point