开发者

Import a dictionary into the current scope as variables

开发者 https://www.devze.com 2023-02-15 03:32 出处:网络
I have a .mat file in which I put data previously processed. When I perform dict = scipy.io.loadmat(\'training_data.mat\')

I have a .mat file in which I put data previously processed. When I perform

dict = scipy.io.loadmat('training_data.mat')

I get back a dict that is like this

{'encoders' : ......, 'decoders' : ....开发者_运维技巧...., 'stuff' : .....}

I want to selectively import the encoders and decoders variables into my current scope. The effect is the same as:

encoders = dict['encoders']
decoders = dict['decoders']

How do I cleanly do this without typing 10-15 lines?


You could import a dictionary d into the global scope using

globals().update(d)

The same thing is impossible for local scopes, since modifying the dictionary returned by locals() results in undefined behaviour.

A slightly hacky trick you could use in this situation is to import the names into the dictionary of an on-the-fly created type:

d = {"encoders": 1, "decoders": 2}
t = type("", (), d)
print t.encoders
print t.decoders

This will at least be slightly more convenient than using d["decoders"] etc.

Alternatively, you could use exec statements to create your variables:

d = {"encoders": 1, "decoders": 2}
for k, v in d.iteritems():
    exec k + " = v"

This could also be done selectively.

0

精彩评论

暂无评论...
验证码 换一张
取 消