3 ms·
This looks really nice. I might be reading the DefaultBox docs wrong, but does it support this: box.might_exist.might_exist.might_exist.desired_key where
by nathancahill 9y ago
This looks really nice. I might be reading the DefaultBox docs wrong, but does it support this:
box.might_exist.might_exist.might_exist.desired_key
where desired_key would return a default value if one of the keys doesn't exist?
I find the bulk of my dict code is checking for keys before access, or using .get('', default) recursively. Gets really hairy for deeply nested dicts.
- bgschiller 9y agoI 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
- elmigranto 9y ago> Gets really hairy for deeply nested dicts. Write a function. `def my_deep_get(dict, keys)`