Safely reading deep nested keys SASamPriceOP 28 Sep, 12:58 edited mission["crew"]["commander"]["name"] crashes if any level is missing. Is there a clean way?
ELElaKowalska28 Sep, 20:38replies: 2Chain .get() with empty dicts as defaults:name = mission.get("crew", {}).get("commander", {}).get("name", "unknown")Readable for 2–3 levels. Deeper than that, it's worth writing a small helper function or checking the structure once when the data comes in.
TOTomBecker29 Sep, 07:41If the data comes from an API, validating it once at the start beats defending every access later.
Comments 4
Join the discussion CommentAlready have an account? Log in
Chain
.get()with empty dicts as defaults:Readable for 2–3 levels. Deeper than that, it's worth writing a small helper function or checking the structure once when the data comes in.
That chain is good enough for my case.
Agreed. The "Nested response" challenge made me realise that.
If the data comes from an API, validating it once at the start beats defending every access later.