Skip to content

Commit 21c2e86

Browse files
Merge pull request #4870 from stevengj/multikey
make D[x,y...] correspond to D[(x,y...)] for a dictionary D
2 parents 6c383d2 + 2eea897 commit 21c2e86

File tree

3 files changed

+11
-0
lines changed

3 files changed

+11
-0
lines changed

base/dict.jl

+5
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,11 @@ function getindex(t::Associative, key)
140140
return v
141141
end
142142

143+
# t[k1,k2,ks...] is syntactic sugar for t[(k1,k2,ks...)]. (Note
144+
# that we need to avoid dispatch loops if setindex!(t,v,k) is not defined.)
145+
getindex(t::Associative, k1, k2, ks...) = getindex(t, tuple(k1,k2,ks...))
146+
setindex!(t::Associative, v, k1, k2, ks...) = setindex!(t, v, tuple(k1,k2,ks...))
147+
143148
push!(t::Associative, key, v) = setindex!(t, v, key)
144149

145150
# hashing objects by identity

doc/stdlib/base.rst

+2
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,8 @@ Dicts can be created using a literal syntax: ``{"A"=>1, "B"=>2}``. Use of curly
642642
As with arrays, ``Dicts`` may be created with comprehensions. For example,
643643
``{i => f(i) for i = 1:10}``.
644644

645+
Given a dictionary ``D``, the syntax ``D[x]`` returns the value of key ``x`` (if it exists) or throws an error, and ``D[x] = y`` stores the key-value pair ``x => y`` in ``D`` (replacing any existing value for the key ``x``). Multiple arguments to ``D[...]`` are converted to tuples; for example, the syntax ``D[x,y]`` is equivalent to ``D[(x,y)]``, i.e. it refers to the value keyed by the tuple ``(x,y)``.
646+
645647
.. function:: Dict()
646648

647649
``Dict{K,V}()`` constructs a hashtable with keys of type K and values of type V.

test/collections.jl

+4
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ for i=10000:20000
3838
end
3939
h = {"a" => 3}
4040
@test h["a"] == 3
41+
h["a","b"] = 4
42+
@test h["a","b"] == h[("a","b")] == 4
43+
h["a","b","c"] = 4
44+
@test h["a","b","c"] == h[("a","b","c")] == 4
4145

4246
let
4347
z = Dict()

0 commit comments

Comments
 (0)