# Dictionary with multiple identical keys

**URL:** https://discourse.julialang.org/t/dictionary-with-multiple-identical-keys/4269
**Category:** New to Julia
**Created:** [June 14, 2017, 12:32pm UTC](https://discourse.julialang.org/t/dictionary-with-multiple-identical-keys/4269 "2017-06-14T12:32:36Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Daniel\_Scheinerman](https://avatars.discourse-cdn.com/v4/letter/d/858c86/32.png) [@Daniel\_Scheinerman](https://discourse.julialang.org/u/Daniel_Scheinerman)
#### Post date: [June 14, 2017, 12:32pm UTC](https://discourse.julialang.org/t/dictionary-with-multiple-identical-keys/4269/1 "2017-06-14T12:32:36Z")

</div>

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!

---

<div class="post-metadata">

### Author: ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)
#### Post date: [June 14, 2017, 12:41pm UTC](https://discourse.julialang.org/t/dictionary-with-multiple-identical-keys/4269/2 "2017-06-14T12:41:42Z")

</div>

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