If you want to use the float key dictionary at multiple places in your program, it might me worth to "hide" the complexity of how it ought to be used (i. e. with rounded keys) in a new dictionary class (full implementation).
Example:
>>> d = FloatKeyDictionary(2, {math.pi: "foo"})
>>> d
{3.14: 'foo'}
>>> d[3.1415]
'foo'
>>> 3.1 in d
False
>>> d[math.e] = "My hovercraft is full of eels!"
>>> d
{3.14: 'foo', 2.72: 'My hovercraft is full of eels!'}
You can find an abridged version with the general idea below:
import abc
import collections.abc
class KeyTransformDictionaryBase(dict, abc.ABC):
@abc.abstractmethod
def __key_transform__(self, key):
raise NotImplementedError
def __contains__(self, key):
return super().__contains__(self.__key_transform__(key))
def __getitem__(self, key):
return super().__getitem__(self.__key_transform__(key))
def __setitem__(self, key, value):
return super().__setitem__(self.__key_transform__(key), value)
def __delitem__(self, key):
return super().__delitem__(self.__key_transform__(key))
class FloatKeyDictionary(KeyTransformDictionaryBase):
def __init__(self, rounding_ndigits, data=None):
super().__init__()
self.rounding_ndigits = rounding_ndigits
if data is not None:
self.update(data)
def __key_transform__(self, key):
return round(key, self.rounding_ndigits)