Safely reading deep nested keys

SamPriceOP edited

mission["crew"]["commander"]["name"] crashes if any level is missing. Is there a clean way?

1

Comments 4

Join the discussion

Already have an account? Log in

  1. ElaKowalskareplies: 2

    Chain .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.

    4
      1. Grace_42

        Agreed. The "Nested response" challenge made me realise that.

        4
    1. TomBecker

      If the data comes from an API, validating it once at the start beats defending every access later.

      3