使用NumPy将多数组保存为NPZ格式后,通过关键字参数加载时触发KeyError的问题排查
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 keyarr_0 - Only the
names=arr_nameargument is correctly stored under the keynames
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

