Should float work as a dictionary key?



  • Should float work as a dictionary key?
    WiPy (name='micropython', version=(1, 8, 6))

    d={0:'reset', 1.0:'on your marks',1.1:'get set'}
    
    TypeError: unsupported type for __hash__: 'float'
    


  • As other responses have suggested.
    float's for keys causes a number of problems.

    if you really need to use the <number>.<number> key format for other reasons.
    try using strings.

    d={"0": 'reset', "1.0": 'on your marks', "1.1": 'get set'}
    print(d["1.1"])
    


  • 22
    down vote
    accepted
    There's no problem using floats as dict keys.

    Just round(n, 1) them to normalise them to your keyspace. eg.

    hash(round(6.84, 1))
    3543446220

    hash(round(6.75, 1))
    3543446220





  • It will be hard to find a good hash function for float. It will depend too much on your value range.

    But the main problem: you will not have a 1:1 relation between the decimal value you type in and the binary value stored in memory. A normal dictionary API does not know anything about a delta to handle this. So you have to implement your own float class with a hash function and an equal operator using a delta.

    I would not recommand to use a lot of float operations on a Py* device. Each float operation generates a new object. This is neither fast nor good for your memory fragmentation. It will be hard to get the memory chunk for a huge dictionary after you calculated the index. Use int as a workaround for fix point calculations as long as possible.


Log in to reply
 

Pycom on Twitter