Julia has a package called UnPack.jl that can convert Dict or NamedTuple to variables. For example, given the Dict
params = Dict(:a=>5.0, :b=>2, :c=>"Hi!")
I can get a
and c
by unpacking the values in the Dict to variables with the same name as the keys:
@unpack a, c = params
Some great features of UnPack.jl are:
a
, c
created in this way will not be treated as "undefined variables" by linting tools;b
, so @unpack
will not create b
. In other words, I have full control on what variables are to be extracted; unneeded variables will not be created. It there a similar (or even equivalent) package in Python to unpack a dict
? In particular, please avoid locals()
, eval
, exec
because either the linting tools cannot recognize the definition of the variables, or they are "dangerous" functions not recommended for use.
It puts new variables in global namespace :(, but:
d = {'a' : 5.0, 'b' : 2, 'c' : "Hi!"}
globals().update((k, d[k]) for k in ['a', 'b', 'c'])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.