Skip to content

Commit 29ae7bc

Browse files
committed
NF - .get() for wrapstruct to provide the same convenience as dict's .get
1 parent 953ea8b commit 29ae7bc

File tree

2 files changed

+9
-0
lines changed

2 files changed

+9
-0
lines changed

nibabel/tests/test_wrapstruct.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,11 @@ def test_mappingness(self):
165165
assert_equal(keys, list(hdr_dt.names))
166166
for key, val in hdr.items():
167167
assert_array_equal(hdr[key], val)
168+
# verify that .get operates as destined
169+
assert_equal(hdr.get('nonexistent key'), None)
170+
assert_equal(hdr.get('nonexistent key', 'default'), 'default')
171+
assert_equal(hdr.get(keys[0]), vals[0])
172+
assert_equal(hdr.get(keys[0], 'default'), vals[0])
168173

169174
def test_endianness_ro(self):
170175
# endianness is a read only property

nibabel/wrapstruct.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,10 @@ def items(self):
341341
''' Return items from structured data'''
342342
return zip(self.keys(), self.values())
343343

344+
def get(self, k, d=None):
345+
''' Return value for the key k if present or d otherwise'''
346+
return (k in self.keys()) and self._structarr[k] or d
347+
344348
def check_fix(self, logger=None, error_level=None):
345349
''' Check structured data with checks '''
346350
if logger is None:

0 commit comments

Comments
 (0)