Interview Prep/Python for DevOps/Language essentials & functions

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.

All Python for DevOps questions Roadmap: Python for automation

More on Language essentials & functions