从 np.load() 加载字典

Load dictionary from np.load()

我有一本字典,我把它保存到一个文件中。

a = {'a':1,'b':2,'c':3,'d':4}
with open('testdata.pickle', 'wb') as f:
    np.save(f,a)

当我尝试加载它时,它returns不可读

b = np.load('testdata.pickle',allow_pickle=True)
print(b)       #{'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(type(b)) #<class 'numpy.ndarray'>
print(b.shape) #()
print(len(b))  #Traceback (most recent call last):
               #File "<stdin>", line 1, in <module>
               #TypeError: len() of unsized object

如何访问这本词典?

尝试直接访问字典也失败了。

>>> b['a']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

正如juanpa.arrivillaga所说,我不应该使用np.save/load。 pickle.dump 和 pickle.load 更好

with open('testdata.pickle', 'wb') as f:
    pickle.dump(a, f)


b = pickle.load(open('testdata.pickle','rb'))

print(b) #{'a': 1, 'b': 2, 'c': 3, 'd': 4}

当您执行 numpy.load() 并希望将项目存储在该文件中时,您需要使用 .item()。在这种情况下,您需要 b.item()

这是因为numpy将字典存储为数组。您将字典保存为 numpy 对象,默认情况下,它是数组。 您可以简单地使用 :

d = b.ravel()[0]

这基本上是从数组中取出字典。然后您可以使用兼容的字典操作。

但是,如果您主要用于保存和加载词典,我建议您改用 pickle。