Install PyYAML

pip install pyyaml

Parse a YAML String

import yaml

yaml_string = """
name: Alice
age: 30
skills:
  - Python
  - YAML
  - Docker
"""

data = yaml.safe_load(yaml_string)
print(data)
# {'name': 'Alice', 'age': 30, 'skills': ['Python', 'YAML', 'Docker']}

Read a YAML File

import yaml

with open('config.yaml', 'r') as f:
    config = yaml.safe_load(f)

print(config['name'])  # access parsed values

Dump Python Data to YAML

import yaml

data = {'name': 'Alice', 'age': 30, 'skills': ['Python', 'YAML']}

# Default flow style=False gives block style (more readable)
print(yaml.dump(data, default_flow_style=False, sort_keys=False))
# name: Alice
# age: 30
# skills:
# - Python
# - YAML

Write a YAML File

import yaml

data = {'name': 'Alice', 'age': 30}

with open('output.yaml', 'w') as f:
    yaml.dump(data, f, default_flow_style=False, allow_unicode=True)

Parse Multiple YAML Documents

import yaml

yaml_string = """
---
name: Alice
---
name: Bob
"""

for doc in yaml.safe_load_all(yaml_string):
    print(doc)

Need to format YAML without writing code?

Paste any YAML into the free online formatter — instant results, no Python environment needed.

Open YAML Formatter →

Frequently Asked Questions

What is the difference between yaml.load and yaml.safe_load?

safe_load only handles basic types (str, int, float, list, dict, bool, None). load can instantiate arbitrary Python objects — a security risk with untrusted YAML. Always use safe_load.

How do I preserve key order when dumping YAML?

Pass sort_keys=False to yaml.dump(). In Python 3.7+, dicts maintain insertion order, so the output will match the order you defined the keys.

How do I handle Unicode characters in YAML?

Pass allow_unicode=True to yaml.dump() to output Unicode characters directly instead of escape sequences.