You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NumPy将多数组保存为NPZ格式后,通过关键字参数加载时触发KeyError的问题排查

KeyError: 't1 is not a file in the archive' when loading NPZ file

Let's break down what's going wrong here and fix it step by step. The issue starts in how you're saving your arrays with np.savez—your current code isn't setting up the archive keys the way you think it is.

Why the KeyError happens

When you call np.savez('data.npz', dict(zip(names,all_arr)), names=arr_name), you're passing the dictionary of arrays as a positional argument. NumPy treats positional arguments as anonymous arrays and assigns them default keys like arr_0, arr_1, etc. Only keyword arguments let you set custom, meaningful keys for your arrays.

In your case:

  • The dictionary {'t1': array([0,...,9]), 't2': ..., 't3': ...} gets saved as a single entry with the key arr_0
  • Only the names=arr_name argument is correctly stored under the key names

That's why trying to access dict_data['t1'] throws a KeyError—there's no entry with that key in the archive.

Fixing the save code

You need to tell np.savez to use the keys from your dictionary as the archive keys. The simplest way is to unpack the dictionary using the ** operator, which converts each key-value pair into a separate keyword argument:

from numpy import load
import numpy as np

names=['t1','t2','t3']
arr_name = np.array(names)
all_arr=[]
for idx,fname in enumerate(names):
    all_arr.append(np.arange(10))

# Unpack the dictionary to assign custom keys to each array
np.savez('data.npz', **dict(zip(names,all_arr)), names=arr_name)

If you prefer a more explicit approach, you can pass each array directly with its key:

# Explicitly map each array to its custom key
np.savez('data.npz', t1=all_arr[0], t2=all_arr[1], t3=all_arr[2], names=arr_name)

Testing the fix

Now when you run your loading code:

dict_data = load('data.npz')
data = dict_data['t1']
print(data)  # Output: [0 1 2 3 4 5 6 7 8 9]

This will work as expected, since 't1' is now a valid key in the NPZ archive.

内容的提问来源于stack exchange,提问作者rpb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 07:12:48