Search code examples
pythonpython-2.7dictionaryfloating-pointint

Why can a floating point dictionary key overwrite an integer key with the same value?


I'm working through http://www.mypythonquiz.com, and question #45 asks for the output of the following code:

confusion = {}
confusion[1] = 1
confusion['1'] = 2
confusion[1.0] = 4

sum = 0
for k in confusion:
    sum += confusion[k]

print sum

The output is 6, since the key 1.0 replaces 1. This feels a bit dangerous to me, is this ever a useful language feature?


Solution

  • You should consider that the dict aims at storing data depending on the logical numeric value, not on how you represented it.

    The difference between ints and floats is indeed just an implementation detail and not conceptual. Ideally the only number type should be an arbitrary precision number with unbounded accuracy even sub-unity... this is however hard to implement without getting into troubles... but may be that will be the only future numeric type for Python.

    So while having different types for technical reasons Python tries to hide these implementation details and int->float conversion is automatic.

    It would be much more surprising if in a Python program if x == 1: ... wasn't going to be taken when x is a float with value 1.

    Note that also with Python 3 the value of 1/2 is 0.5 (the division of two integers) and that the types long and non-unicode string have been dropped with the same attempt to hide implementation details.