Given a dictionary, how to create variables that point to the keys’ value.
This is easy to do manually:
dict = Dict(:a => "newton", :b => "einstein", :c => "hawking")
a = dict[:a]
a # => "newton"
b = dict[:b]
b # => "einstein"
but how to do it automatically? My mind has gone blank…
1 Like
Maybe like this?
julia> dict = Dict(:a => "newton", :b => "einstein", :c => "hawking");
julia> for key in keys(dict)
@eval const $key = dict[$(QuoteNode(key))]
end
julia> a, b, c
("newton", "einstein", "hawking")
5 Likes
Thanks, that’s brilliant…
I had
for key in keys(dict)
@eval const $key = dict[$key]
end
which didn’t work - what does the QuoteNode
do?
rdeits
January 23, 2019, 1:42pm
5
You need the quote node to ensure that the key is represented as a quoted symbol in the resulting expression. That is, you need it in order to get an expression like dict[:x]
instead of dict[x]
4 Likes
On reflection I don’t really know what a ‘node’ is, which is why QuoteNode
s weren’t easy to understand.
1 Like