Python - YAML

Overview

Estimated time: 15–25 minutes

Use PyYAML to read and write YAML. Learn safe loading, dumping, and caveats around types and anchors.

Learning Objectives

  • Load/dump YAML safely.
  • Understand common YAML features (lists, maps, anchors) and pitfalls.

Examples

# pip install pyyaml
import yaml

data = yaml.safe_load("""
users:
  - id: 1
    name: Ada
""")
print(data["users"][0]["name"])  # Ada

print(yaml.safe_dump(data, sort_keys=False))

Guidance & Patterns

  • Prefer safe_load/safe_dump; avoid load without a loader.
  • Consider JSON for simpler, tool-friendly configs; YAML for human-authored configs.

Best Practices

  • Validate schema; avoid implicit type surprises (e.g., unquoted values).

Exercises

  1. Convert a YAML config to JSON and back, preserving key order.
  2. Demonstrate YAML anchors/aliases and how they serialize.