Databases Reference
In-Depth Information
When retrieving elements, we get back the actual value, not an intermediate object like
a
Dataset
:
>>>
dset
.
attrs
[
'title'
]
'Dataset from third round of experiments'
>>>
dset
.
attrs
[
'sample_rate'
]
100000000.0
>>>
dset
.
attrs
[
'run_id'
]
144
Like groups (and Python dictionaries), iterating over the
.attrs
object provides the
attribute names:
>>>
[
x
for
x
in
dset
.
attrs
]
[u'title', u'sample_rate', u'run_id']
You'll notice that like object names, the names of attributes are always returned as “text”
strings; this means
unicode
on Python 2, which explains the
u
prefix.
Attributes don't have the same strict rules as groups for item deletion. You can freely
overwrite attributes just by reusing the name:
>>>
dset
.
attrs
[
'another_id'
]
=
42
>>>
dset
.
attrs
[
'another_id'
]
=
100
Trying to access missing attributes raises
KeyError
, although as with
Group
you don't
get the name of the missing attribute:
>>>
del
dset
.
attrs
[
'another_id'
]
>>>
dset
.
attrs
[
'another_id'
]
KeyError: "can't open attribute (Attribute: Can't open object)"
There are also the usual methods like
iterkeys
,
iteritems
,
values
, and so on. They
all do what you expect:
>>>
[(
name
,
val
)
for
name
,
val
in
dset
.
attrs
.
iteritems
()]
[(u'title', 'Dataset from third round of experiments'),
(u'sample_rate', 100000000.0),
(u'run_id', 144)]
There generally aren't that many attributes attached to an object, so worrying about
items
versus
iteritems
, etc., is less important from a performance perspective.
There is also a
get
method that (unlike the
Group
version) is a dictionary-style
get
:
>>>
dset
.
attrs
.
get
(
'run_id'
)
144
>>>
print
dset
.
attrs
.
get
(
'missing'
)
None