If the object you want save is a nested dictionary, with numeric values, then it could be recreated with the group/set
structure of a H5 file.
A simple recursive function would be:
def write_layer(gp, adict):
for k,v in adict.items():
if isinstance(v, dict):
gp1 = gp.create_group(k)
write_layer(gp1, v)
else:
gp.create_dataset(k, data=np.atleast_1d(v))
In [205]: dd = {'value1': 0.09, 'state': {'angle_rad': 0.034903, 'value2': 0.83322}, 'value3': 0.3}
In [206]: f = h5py.File('test.h5', 'w')
In [207]: write_layer(f, dd)
In [208]: list(f.keys())
Out[208]: ['state', 'value1', 'value3']
In [209]: f['value1'][:]
Out[209]: array([ 0.09])
In [210]: f['state']['value2'][:]
Out[210]: array([ 0.83322])
You might want to refine it and save scalars as attributes rather full datasets.
def write_layer1(gp, adict):
for k,v in adict.items():
if isinstance(v, dict):
gp1 = gp.create_group(k)
write_layer1(gp1, v)
else:
if isinstance(v, (np.ndarray, list)):
gp.create_dataset(k, np.atleast_1d(v))
else:
gp.attrs.create(k,v)
In [215]: list(f.keys())
Out[215]: ['state']
In [218]: list(f.attrs.items())
Out[218]: [('value3', 0.29999999999999999), ('value1', 0.089999999999999997)]
In [219]: f['state']
Out[219]: <HDF5 group "/state" (0 members)>
In [220]: list(f['state'].attrs.items())
Out[220]: [('value2', 0.83321999999999996), ('angle_rad', 0.034903000000000003)]
Retrieving the mix of datasets and attributes is more complicated, though you could write code to hide that.
Here's a structured array approach (with a compound dtype)
Define a dtype that matches your dictionary structure. Nesting like this is possible, but can be awkward if too deep:
In [226]: dt=[('state',[('angle_rad','f'),('value2','f')]),
('value1','f'),
('value3','f')]
In [227]: dt = np.dtype(dt)
Make a blank array of this type, with several records; fill in one record with data from your dictionary. Note that the nest of tuples has to match the dtype nesting. More generally structured data is provided as a list of such tuples.
In [228]: arr = np.ones((3,), dtype=dt)
In [229]: arr[0]=((.034903, 0.83322), 0.09, 0.3)
In [230]: arr
Out[230]:
array([(( 0.034903, 0.83322001), 0.09, 0.30000001),
(( 1. , 1. ), 1. , 1. ),
(( 1. , 1. ), 1. , 1. )],
dtype=[('state', [('angle_rad', '<f4'), ('value2', '<f4')]), ('value1', '<f4'), ('value3', '<f4')])
Writing the array to the h5 file is straight forward:
In [231]: f = h5py.File('test1.h5', 'w')
In [232]: g = f.create_dataset('data', data=arr)
In [233]: g.dtype
Out[233]: dtype([('state', [('angle_rad', '<f4'), ('value2', '<f4')]), ('value1', '<f4'), ('value3', '<f4')])
In [234]: g[:]
Out[234]:
array([(( 0.034903, 0.83322001), 0.09, 0.30000001),
(( 1. , 1. ), 1. , 1. ),
(( 1. , 1. ), 1. , 1. )],
dtype=[('state', [('angle_rad', '<f4'), ('value2', '<f4')]), ('value1', '<f4'), ('value3', '<f4')])
In theory we could write functions like write_layer
that work through your dictionary and construct the relevant dtype and records.