Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to define new variables by iterating a dictionary (Julia)

Consider a dictionary d in Julia which contains a thousand of keys. Each key is a symbol and each value is an array. I can access to the value associated with the symbol :S1 and assign it to the variable k1 via

k1 = d[:S1]

Now assume I want to define the new variables k2, k3, k4, ..., k10 by repeating the same procedure for the special keys :S1 ... :S10 (not for all the keys in the dictionary). What is the most efficient way to do it? I have the impression this can be solved using metaprogramming but not sure about that.

like image 681
dapias Avatar asked Oct 21 '25 15:10

dapias


1 Answers

The easy way is to use Parameters.jl.

using Parameters
d = Dict{Symbol,Any}(:a=>5.0,:b=>2,:c=>"Hi!")
@unpack a, c = d
a == 5.0 #true
c == "Hi!" #true

BTW, this doesn't use eval.

like image 165
Chris Rackauckas Avatar answered Oct 23 '25 07:10

Chris Rackauckas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!