From 2eea8970b18249476e635fc079f14353ab1ba25e Mon Sep 17 00:00:00 2001 From: "Steven G. Johnson" Date: Wed, 20 Nov 2013 17:22:46 -0500 Subject: [PATCH] make D[x,y...] correspond to D[(x,y...)] for a dictionary D; see #4803 --- base/dict.jl | 5 +++++ doc/stdlib/base.rst | 2 ++ test/collections.jl | 4 ++++ 3 files changed, 11 insertions(+) diff --git a/base/dict.jl b/base/dict.jl index 699524f19082f..b42e89d1bafbd 100644 --- a/base/dict.jl +++ b/base/dict.jl @@ -140,6 +140,11 @@ function getindex(t::Associative, key) return v end +# 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::Associative, k1, k2, ks...) = getindex(t, tuple(k1,k2,ks...)) +setindex!(t::Associative, v, k1, k2, ks...) = setindex!(t, v, tuple(k1,k2,ks...)) + push!(t::Associative, key, v) = setindex!(t, v, key) # hashing objects by identity diff --git a/doc/stdlib/base.rst b/doc/stdlib/base.rst index 5cafa43e51f9a..c836656c1e874 100644 --- a/doc/stdlib/base.rst +++ b/doc/stdlib/base.rst @@ -642,6 +642,8 @@ Dicts can be created using a literal syntax: ``{"A"=>1, "B"=>2}``. Use of curly As with arrays, ``Dicts`` may be created with comprehensions. For example, ``{i => f(i) for i = 1:10}``. +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)``. + .. function:: Dict() ``Dict{K,V}()`` constructs a hashtable with keys of type K and values of type V. diff --git a/test/collections.jl b/test/collections.jl index cfcb44e83473c..200b06649e0fd 100644 --- a/test/collections.jl +++ b/test/collections.jl @@ -38,6 +38,10 @@ for i=10000:20000 end h = {"a" => 3} @test h["a"] == 3 +h["a","b"] = 4 +@test h["a","b"] == h[("a","b")] == 4 +h["a","b","c"] = 4 +@test h["a","b","c"] == h[("a","b","c")] == 4 let z = Dict()