Get on None value doesn't return default value of get
Question:
When I do a get
on a dict that has the value None
, it returns a None
rather than the default
value of the get
d = {"a": None}
d.get("a", {}).get("truc")
Is there any way to do this in one line?
Answers:
None
is still a value and the key exists, so yeah, you won’t get the default value. If you need a truthy value, do this:
(d.get('a') or {}).get('truc')
When I do a get
on a dict that has the value None
, it returns a None
rather than the default
value of the get
d = {"a": None}
d.get("a", {}).get("truc")
Is there any way to do this in one line?
None
is still a value and the key exists, so yeah, you won’t get the default value. If you need a truthy value, do this:
(d.get('a') or {}).get('truc')