Databases Reference
In-Depth Information
By the way, you don't have to manually create nested groups one at a time. If you supply
a full path, HDF5 will create all the intermediate groups for you:
>>>
out
=
f
.
create_group
(
'/some/big/path'
)
>>>
out
<HDF5 group "/some/big/path" (0 members)>
The same goes for creating datasets; just supply the full path you want and HDF5 will
fill in the missing pieces.
Group Basics
If you remember nothing else from this chapter, remember this:
groups work mostly like
dictionaries
. There are a couple of holes in this abstraction, but on the whole it works
surprisingly well. Groups are iterable, and have a subset of the normal Python dictionary
API.
Let's add another few objects to our file for the examples that follow:
>>>
f
[
"Dataset1"
]
=
1.0
>>>
f
[
"Dataset2"
]
=
2.0
>>>
f
[
"Dataset3"
]
=
3.0
>>>
subgroup
[
"Dataset4"
]
=
4.0
Dictionary-Style Access
You got a hint of this dictionary-like behavior from the syntax
group[name] =
object
.
Objects can be retrieved from a group by name:
>>>
dset1
=
f
[
"Dataset1"
]
Unlike normal Python dictionaries, you can also use POSIX-style paths to directly access
objects in subgroups, without having to tediously open all the groups between here and
there:
>>>
dset4
=
f
[
"SubGroup/Dataset4"
]
# Right
>>>
dset4
=
f
[
"SubGroup"
][
"Dataset4"
]
# Works, but inefficient
Attempting to access an empty group raises
KeyError
, although one irritating thing
about h5py is that you don't get the name of the missing object in the exception:
>>>
f
[
'BadName'
]
KeyError: "unable to open object (Symbol table: Can't open object)"
There's also the familar
get
method, which is handy if you don't want to raise an ex‐
ception:
>>>
out
=
f
.
get
(
"BadName"
)
>>>
print
out
None