How can I access multiple values of a dictionary using a tuple of keys?

How can I access multiple values of a dictionary using a tuple of keys?

Note that the original poster on Slack cannot see your response here on Discourse. Consider transcribing the appropriate answer back to Slack, or pinging the poster here on Discourse so they can follow this thread.
(Original message :slack:) (More Info)

1 Like

I found this other post, but it doesn’t seem to work in Julia 1.5

1 Like

By @pfitzseb:

I’d just broadcast getindex :

julia> d = Dict(:a => 1, :b => 2, :c => 3)
Dict{Symbol,Int64} with 3 entries:
:a => 1
:b => 2
:c => 3julia> getindex.(Ref(d), (:a, :b, :c))
(1, 2, 3)

The Ref(...) does the trick.

6 Likes

Do you know what the Ref is necessary?

The Ref is necessary for the Dict to be treated as an scalar by the broadcast instead of a collection. Wrapping in an unitary tuple would have the same effect: getindex.((d,), (:a, :b, :c)).

1 Like

I have found the following to benchmark slightly faster than the Ref method:

tuple((d[i] for i in (:a, :b, :c))...)

This has the added bonus of also not needing the tuple or splatting (...) if you are only iterating through results anyway (or replacing tuple with another function). With the tuple and the splatting, this will produce the same result as the Ref method.