How do you safely read nested keys from an API response?
BeginnerConceptLanguage essentials & functions
Answer
Use dict.get() with defaults so a missing key does not raise KeyError:
name = next((t["Value"] for t in inst.get("Tags", []) if t["Key"] == "Name"), "unnamed")
public_ip = inst.get("PublicIpAddress") # None if absent
state = inst.get("State", {}).get("Name", "unknown")
Use d[key] when the key must exist and a crash is the right behaviour; .get() when absence is normal. AWS omits keys like Tags and PublicIpAddress entirely rather than returning empty values.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner