'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:


Maybe like this?

julia> dict = Dict(:a => "newton", :b => "einstein", :c => "hawking");

julia> for key in keys(dict)
           @eval const $key = dict[$(QuoteNode(key))]

julia> a, b, c
("newton", "einstein", "hawking")


Thanks, that’s brilliant…


I had

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

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]


In addition, there is some documentation about it:



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