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>You can round it to the accuracy you can accept:</p>

<pre><code>&gt;&gt;&gt; hash(round(3.1, 2))
2093862195
&gt;&gt;&gt; hash(round(3.1000000000000001, 2))
2093862195
</code></pre>

python pandas dictionary floating-point