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?

Asked By: MathAng

||

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')
Answered By: deceze
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.