Accessing Dict of tuples

I just realized you can access a Dict of tuples passing the tuple with the extra parens. Has this always been the case? Or is this a recent addition to the language?

For example,

d = Dict((a,i) => randn() for a = 1:5 for i = 1:10)
@assert d[3,4] == d[(3,4)]

Why is the tuple here being automatically splatted?

@edit d[3,4] shows the relevant code:

# t[k1,k2,ks...] is syntactic sugar for t[(k1,k2,ks...)].  (Note
# that we need to avoid dispatch loops if setindex!(t,v,k) is not defined.)
getindex(t::AbstractDict, k1, k2, ks...) = getindex(t, tuple(k1,k2,ks...))

and this works at least as far back as Julia 0.4.

Note that the parens aren’t ‘extra’: the d[(3, 4)] syntax is directly accessing the dictionary at the key (3, 4), while the d[3, 4] syntax is just syntactic sugar to save some keystrokes.

2 Likes