【问题标题】:save a netsted dictionary to hdf or netCDF将 netsted 字典保存到 hdf 或 netCDF
【发布时间】:2020-05-04 16:47:59
【问题描述】:

通常,将字典保存到 hdf 或 netCDF 很简单。例如here。 但是如何处理嵌套字典。例如以下字典:

test = {'temp': {'unit': 'K', 'data': [273.,298.,315.]}, 'press': {'unit': 'hPa', 'data': [800.,900.,1000.]}}

请注意,嵌套可以持续到多个级别。所以我需要 netCDF 或 hdf 组内的子组

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: python python-3.x dictionary netcdf hdf


【解决方案1】:

没关系,我想出了答案

将 numpy 导入为 np 导入 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))

【讨论】:

    【解决方案2】:

    也许像这个函数这样的东西可以提供帮助。我在这里为您的示例对其进行了自定义,但是如果您可以提供属性字典并使其类似于“数据”的工作方式,效果会更好。我正在使用 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
    

    【讨论】:

    • 问题是字典可以嵌套在多个级别。根据应用程序,最佳数量可能会有所不同。
    猜你喜欢
    • 2022-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多