Reputation: 3460
I am struggling with the following problem: given a dictionary with an numpy array as a value, for example, a={'xarray':np.ones((2,2))}
, I want to save the array into npz file with name from the dictionary key:
np.savez('test.npz',a.keys()=a['xarray'])
The error is in a.keys
:
SyntaxError: keyword can't be an expression.
I need to convert the key into an expression somehow. I tried to use eval
function but didn't succeed.
Thanks, Mikhail
Edit:
In order to clarify things, I want the result to be equivalent to the following:
np.savez('test.npz', xarray = np.ones((2,2)))
The name of my array is specified in the first key of the dictionary, while the array itself in the first value: a={'xarray':np.ones((2,2))}
.
Attempting: np.savez('test.npz',format(list(a.keys())[0])=list(a.values())[0])
returns again SyntaxError: keyword can't be an expression
Upvotes: 2
Views: 871
Reputation: 384
If I understand you correctly you should try something line that: np.savez('{}.npz'.format(list(a.keys())[0]))
. This will set a filename to a first key in a given dictionary.
The error that you get is correct since you are trying to set a.keys()
to be the value of a['xarray']
which is an expression. Moreover, to my very best knowledge python will not allow that.
Edit: I am just after the lecture of what np.savez function does and I misunderstood you. So the correct thing (if I am correct now) is to do this:
kwargs = {key: a[key] for key in a.keys()}
np.savez('test.npz', **kwargs)
Please try and say if this is what you want :)
Edit 2: For having only first key:
kwargs = {key: a[key] for key in [list(a.keys())[0]]}
np.savez('test.npz', **kwargs)
Upvotes: 3