一般来说,将字典保存为hdf或netCDF是很直接的。例如 此处.但如何处理嵌套的字典。例如下面的字典。
test = {'temp': {'unit': 'K', 'data': [273.,298.,315.]}, 'press': {'unit': 'hPa', 'data': [800.,900.,1000.]}}
请注意,嵌套可以持续到几层。所以我需要在netCDF或hdf的组内建立子组。
没关系,我知道答案了
导入numpy作为npimport h5py。
def dict2hdf5(filename, dic):
with h5py.File(filename, 'w') as h5file:
recursive_dict2hdf5(h5file, '/', dic)
def recursive_dict2hdf5(h5file, path, dic):
for key, item in dic.items():
if not isinstance(key, str):
key = str(key)
if isinstance(item, (np.ndarray, np.int64, np.float64, str, bytes)):
h5file[path + key] = item
elif isinstance(item, list):
h5file[path + key] = np.array(item)
elif isinstance(item, dict):
recursive_dict2hdf5(h5file, path + key + '/',
item)
else:
raise ValueError('Cannot save %s type' % type(item))
也许这个函数可以帮到你。我在这里为你的例子定制了这个函数,但如果你能提供一个属性字典,并使它的工作方式类似于 "data",效果会更好。我使用xarray来演示如何获得数据集变量,但你可以将这个想法转移到你选择的工具上。
import xarray as xr
def create_variable(dataset, var, test, dimensions):
data = test[var]['data']
attrs = {'unit':test[var]['unit']}
v = xr.Variable(dimensions, data, attrs=attrs)
dataset[var] = v
return var