Interview Prep/Python for DevOps/Language essentials & functions

Write a list, dict and set comprehension for a realistic ops task.

BeginnerConceptLanguage essentials & functions
Answer
instances = [...]  # from describe_instances

running_ids = [i["InstanceId"] for i in instances if i["State"]["Name"] == "running"]

tags_by_id = {i["InstanceId"]: {t["Key"]: t["Value"] for t in i.get("Tags", [])}
              for i in instances}

instance_types = {i["InstanceType"] for i in instances}

Comprehensions are faster than an explicit append loop and read as "what" rather than "how". If one needs more than one if and one for, write a normal loop for readability.

All Python for DevOps questions Roadmap: Python for automation

More on Language essentials & functions