'export' dictionary keys as variables


#1

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… :no_mouth:


#2

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")

#3

Thanks, that’s brilliant…


#4

I had

for key in keys(dict)
           @eval const $key = dict[$key]
       end

which didn’t work - what does the QuoteNode do?


#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]


#6

In addition, there is some documentation about it:

https://docs.julialang.org/en/v1/manual/metaprogramming/#QuoteNode-1
https://docs.julialang.org/en/v1/devdocs/ast/#Quote-expressions-1


#7

On reflection I don’t really know what a ‘node’ is, which is why QuoteNodes weren’t easy to understand.