Accessing multiple values of a dictionary

The only way I found to access multiple values of a dictionary is:

get.(dictionary, ["a", "b", "c"], 0)

I propose the following syntax:

dictionary.["a", "b", "c"]

https://github.com/JuliaLang/julia/issues/19169

There are two fairly compelling potential meanings of x.[y]. It’s not yet clear which one is a better choice, and we’re not really considering adding new features until 1.0 is well out the door.

1 Like

You could also broadcast getindex if you don’t need a default:

julia> dictionary = Dict(:a => 1, :b => 2, :c => 3, :d => 4)
Dict{Symbol,Int32} with 4 entries:
  :d => 4
  :a => 1
  :b => 2
  :c => 3

julia> get.(dictionary, [:a, :b, :c, :e], 0)
4-element Array{Int32,1}:
 1
 2
 3
 0

julia> @which dictionary[:d]
getindex(h::Dict{K,V}, key) where {K, V} in Base at dict.jl:473

julia> getindex.(dictionary, [:a, :b, :c])
3-element Array{Int32,1}:
 1
 2
 3

julia> getindex.(dictionary, [:a, :b, :c, :e])
ERROR: KeyError: key :e not found
2 Likes

Or do something like:

julia> macro get(indexing)
           indexing.head ≠ :. && error("syntax: expected: `d.[ks...]`.")
           dict = indexing.args[1]
           indexing.args[1] = :getindex
           indexing.args[2].head = :tuple
           unshift!(indexing.args[2].args, dict)
           indexing
       end
@get (macro with 1 method)

julia> @get dictionary.[:a, :b, :c]
3-element Array{Int32,1}:
 1
 2
 3

Just as an example.

These examples don’t seem to work in Julia 1.5. See How can I access multiple values of a dictionary using a tuple of keys? for a fix.

1 Like

unshift! wasn’t defined. So I recreated the funciton like this:

macro get(indexing)
	indexing.head ≠ :. && error("syntax: expected: `d.[ks...]`.")
	dict = indexing.args[1]
	indexing.args[1] = :getindex
	indexing.args[2].head = :tuple
	indexing.args[2].args = [Expr(:tuple, dict); indexing.args[2].args]
	indexing
end

Not sure if there isn’t a better one…