Turn the dictionary keys into variable names with same values in Python from .mat Matlab files using scipy.io.loadmat

Viewed 15423

I am trying to take a basic dictionary temp = {'key':array([1,2])} loaded from a .mat file with scipy.io.loadmat. Turn the keys in the Python dictionary file returned by loadmat() into variable names with values the same as the representing keys.

So for example:

temp = {'key':array([1,2])}

turned into

key = array([1,2])

I know how to grab the keys with temp.keys(). Then grabbing the items is easy but how do I force the list of strings in temp.keys() to be variable names instead of strings.

I hope this makes sense but this is probably really easy I just can't think how to do it.

Cheers

6 Answers

To use exec() is more simple as hdhagman answered. I write more simple code.

temp = {'key':[1,2]}

for k, v in temp.items():
    exec("%s = %s" % (k, v))

print(key) => [1,2]

None of the answers above worked for me with numpy arrays and other non-built-in types. However, the following did:

import numpy as np
temp = {'a':np.array([1,2]), 'b': 4.3, 'c': 'foo', 'd':np.matrix([2,2])}
for var in temp.keys():
    exec("{} = temp['{}']".format(var, var))

Note the order of the quotes. This allows var to be treated as a variable in the first instance, and then as a key in the second instance, indexing into the temp dictionary.

Of course, the usual disclaimers about the dangers of exec() and eval() still apply, and you should only run this on input you absolutely trust.

Related