'export' dictionary keys as variables

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:

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?

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

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

1 Like

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

1 Like