Dictionary with multiple identical keys

I accidentally created a dictionary with multiple identical keys recently. The following code encapsulates what I encountered.

function break_dict(n)
D = Dict()
r = zeros(Int16,n)
for i=1:n
r[i] += 1
D[r] = sum(r)
end
D, r
end

If you call:

D, r = break_dict(5)

it returns a dictionary with all keys equal to [1,1,1,1,1] and values 1,2,3,4,5. If you replace “D[r] = sum(r)” with “D[copy(r)] = sum(r)” then you do get five distinct keys as I had initially expected. I am used to Python where keys are immutable so this kind of behavior doesn’t happen. I undertand that “r” is the key not its value. Still having a dictionary with equal keys seems like undesirable behavior. For example, if you ask

length(D)

it returns 5

However,

length(Set(collect(keys(D))))

returns 1. Also,

D[r]

returns 5

D[ [1,1,1,1,0] ]

gives an error since that is not a key (though that value was a key at one point in the loop), but

r[end] = 0
D[r]

returns 4.

Thanks for insights!

We allow mutable keys for flexibility but you must not mutate them in a way that can change their hash and isequal.

1 Like