Dict with Float64 and Int keys of the same value?


#1
d = Dict()
d[1.0] = "hello"
d[1] = "goodbye"
print(d)
# ==> 
# Dict{Any,Any} with 1 entry:
#   1 => "goodbye

So 1.0 and 1 are treated as the same key. Although this behavior makes sense in some contexts, I wonder if there’s a way to have both keys with different values?


#2

ObjectIdDict keys objects on === (i.e. identity).


#3

Thanks, indeed this works Float64 vs Int case. But using ObjectIdDict also has an unfortunate side effect of not finding keys of other types:

d = ObjectIdDict()
d[1.0] = "hello"
d[1] = "goodbye"
print(d)
# ObjectIdDict with 2 entries:
#  1   => "goodbye"
#  1.0 => "hello"
# good!

d["x"] = "bonjour"
d["x"]
# ERROR: KeyError: key "x" not found

Any other option that also preserves behavior for non-numeric types?


#4

That is fixed on master since String is now officially an immutable type and "hello" === "hello" unlike on 0.6. On 0.5 (or otherwise), if you need some custom hybrid behavior, normalize the keys before inserting or looking up.


#5

Thanks, using string(key) instead of actual key worked for me.