Taylor
Taylor

Reputation: 127

Loading dictionary stored as .npz fails

l have a dictionary store at once as one object using np.savez when l open it with np.load as follow :

l get the following :

my_dic=np.load('/home/values.npz')
my_dic.files
['scores']

However when l try :

my_dic['scores'] # len(my_dic['scores'])=1 but contains 3000 keys and 3000 values

it outputs all the keys and values as one object.

Is there any way to access the values and keys ?

something like :

for k,values in my_dic['scores'].items():

    # do something

Thank you

Upvotes: 1

Views: 3091

Answers (2)

Taylor
Taylor

Reputation: 127

Following the indications given by @hpalj, l did the following to solve the problem:

x=list(my_dic['scores'].item()) #allows me to get the keys 
keys=[]
values=[]
for i in np.arange(len(x))
  value=my_dic['scores'].item()[x[i]]
  values.append(value)
  keys.append(x[i])

final_dic=dict(zip(keys,values))

Upvotes: 0

hpaulj
hpaulj

Reputation: 231475

Sounds like you did:

In [80]: np.savez('test.npz', score={'a':1, 'b':2})

In [81]: d = np.load('test.npz')
In [83]: d.files
Out[83]: ['score']
In [84]: d['score']
Out[84]: array({'a': 1, 'b': 2}, dtype=object)

This is a 1 item array with a object dtype. Extract that item with item():

In [85]: d['score'].item()
Out[85]: {'a': 1, 'b': 2}

If instead I save the dictionary with kwargs syntax:

In [86]: np.savez('test.npz', **{'a':1, 'b':2})
In [87]: d = np.load('test.npz')
In [88]: d.files
Out[88]: ['a', 'b']

Now each dictionary key is a file in the archive:

In [89]: d['a']
Out[89]: array(1)
In [90]: d['b']
Out[90]: array(2)

Upvotes: 1

Related Questions