2 ms·
I also found myself doing that pretty often, so I wrote this: def nget(d, *ks, **kwargs): for k in ks: d = d.get(k) if d is
by bgschiller 9y ago
I also found myself doing that pretty often, so I wrote this:
def nget(d, *ks, **kwargs):
for k in ks:
d = d.get(k)
if d is None:
return kwargs.get('default')
return d
>>> d = {'a': {'b': {'c': 12 }}}
>>> nget(d, 'a', 'd', 'c', default='Not Found!')
'Not Found!'
>>> nget(d, 'a', 'b', 'c')
12
- staz 9y agoYour implementation suffer from a bug, if the final item is None it will return the default instead of None. A better implementation would be: def rget(d, *ks, **kwargs): for k in ks: if k not in d: return kwargs.get('default') d = d[k] return d