I'm about to create a dictionary where each value has a numeric key, obtained by an experimental calculation.
I know that double
and any other floating-point type is not well suited to be used as a key, since it's hard to compare two floating-point numbers regarding uniqueness or equality.
Does anyone knows if Decimal
is a good candidate with this respect? The alternative would be to convert the double to string with a given precision, but that sounds to me like an inelegant workaround.
For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable. Values, on the other hand, can be any type and can be used more than once.
Yes. "...can be any immutable type; strings and numbers can always be keys..." Literally from the link you posted: "Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys."
The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
There is not much difference between using float
or decimal
as key in dictionary. Both represent number with exponent - so both suffer from the same comparison issue just in different scale.
Either would be ok for Dictionary if you need bit-wise equality, if you need to keys for "about the same value" you need to make it custom key which would round values in some known way to put similar results in the same bucket...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With