Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectorized indexing for a dictionary

Tags:

julia

I would like to find a succinct syntax in Julia for indexing a dictionary in a vectorized manner. In R, I would do the following:

dict <- c("a" = 1, "b" = 2)
keys <- c("a", "a", "b", "b", "a")
dict[keys]

In Julia, if I have a dict and keys like this,

dict = Dict(:a => 1, :b => 2)
keys = [:a, :a, :b, :b, :a]

then I can achieve the desired result using a list comprehension:

julia> [dict[key] for key in keys]
5-element Array{Int64,1}:
 1
 1
 2
 2
 1

Is there a more succinct vectorized syntax, similar to the R syntax?

like image 234
Cameron Bieganek Avatar asked Mar 07 '19 01:03

Cameron Bieganek


1 Answers

getindex.(Ref(dict), keys)

You can wrap it in Ref so you don't need to [] it.

like image 63
xiaodai Avatar answered Oct 18 '22 12:10

xiaodai