3 ms·
> Of course this only works at one level and not arbitrarily deeply It does though, you can chain as many of these as you want: some_dict.get("level_1_key
by ddejohn 3y ago
> Of course this only works at one level and not arbitrarily deeply
It does though, you can chain as many of these as you want:
some_dict.get("level_1_key", {}).get("level_2_key", {}).get("level_3_key", {})...
edit:
>> but you still need to check for None with this code
> Not sure what you mean here. You only have to check for None if you use `.get("key")` and don't provide a fallback value.
GP was talking about `{"foo": None}` and trying to drill deeper, which I misunderstood. Still, a simple try/except allows you to short-circuit the deeply nested access.
- smilliken 3y agoThe issue is if the dictionary has a key defined and the value is None. Your get expression will return None, causing your next access to raise an error.
- ddejohn 3y agoAh, I see. Still, I'd just catch that exception and move on because it's obvious you won't have anything more deeply nested anyway. Blowing up on `None` is an easy short-circuit.
- kh_hk 3y ago>>> foo = {"foo": None} >>> print(foo.get('foo', {}).get('bar')) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'NoneType' object has no attribute 'get' >>> print((foo.get('foo') or {}).get('bar')) None
- ddejohn 3y agoRight, see my other comment: > Blowing up on `None` is an easy short-circuit. The thing being discussed is attempting to access deeply nested values, so short-circuiting here is a win-win. I.e., you wouldn't want to unnecessarily traverse tons of empty dictionaries using the `.get() or {}` trick.