How to Convert Python List to YAML in Python

This tutorial guides you through various methods to transform Python lists into YAML

You’ll learn to use libraries like pyyaml and ruamel.yaml, explore manual conversion, and more.

 

 

Using pyyaml

You can use the pyyaml library to convert a Python list to YAML.

import yaml
egyptian_names = ["Ahmed", "Fatma", "Omar", "Nour"]
yaml_data = yaml.dump(egyptian_names)
print(yaml_data)

Output:

- Ahmed
- Fatma
- Omar
- Nour

The list egyptian_names is converted to YAML format using yaml.dump().

 

Using ruamel.yaml

The ruamel.yaml library preserves YAML formatting and supports YAML 1.2.

from ruamel.yaml import YAML
from io import StringIO
cities = ["Cairo", "Alexandria", "Giza", "Luxor"]
yaml = YAML()
stream = StringIO()
yaml.dump(cities, stream)
yaml_data = stream.getvalue()
print(yaml_data)

Output:

- Cairo
- Alexandria
- Giza
- Luxor

The list cities is converted to YAML format using ruamel.yaml, and the output is captured in a StringIO stream.

 

Manual Conversion

For simple lists, you can manually format the list into a YAML string.

fruits = ["Apple", "Banana", "Cherry"]
yaml_data = "- " + "\n- ".join(fruits)
print(yaml_data)

Output:

- Apple
- Banana
- Cherry

By joining the list items with "- " and newlines, you create a YAML-formatted sequence without external libraries.

 

Performance Benchmark

To benchmark the speed of converting a Python list to YAML using different methods, you can use the timeit module in Python.

import timeit
import yaml
from ruamel.yaml import YAML
import io
import random
import string
def generate_large_data(size=1000):
    return [
        {
            "id": i,
            "name": ''.join(random.choices(string.ascii_letters, k=10)),
            "value": random.random(),
            "nested": {
                "numbers": [random.randint(0, 100) for _ in range(10)],
                "letters": ''.join(random.choices(string.ascii_letters, k=20))
            }
        }
        for i in range(size)
    ]
large_data = generate_large_data()

# Function using pyyaml
def convert_with_pyyaml():
    return yaml.dump(large_data)

# Function using ruamel.yaml
def convert_with_ruamel():
    yaml = YAML()
    stream = io.StringIO()
    yaml.dump(large_data, stream)
    return stream.getvalue()

# Manual conversion function
def manual_conversion():
    def convert(item):
        if isinstance(item, dict):
            return '{' + ', '.join(f'{k}: {convert(v)}' for k, v in item.items()) + '}'
        elif isinstance(item, list):
            return '[' + ', '.join(convert(i) for i in item) + ']'
        else:
            return repr(item)
    return convert(large_data)
pyyaml_time = timeit.timeit(convert_with_pyyaml, number=10)
ruamel_time = timeit.timeit(convert_with_ruamel, number=10)
manual_time = timeit.timeit(manual_conversion, number=10)
print(f"PyYAML conversion time: {pyyaml_time:.6f} seconds")
print(f"ruamel.yaml conversion time: {ruamel_time:.6f} seconds")
print(f"Manual conversion time: {manual_time:.6f} seconds")

Output:

pyyaml conversion time: 3.418463 seconds
ruamel.yaml conversion time: 11.975762 seconds
Manual conversion time: 0.146680 seconds

Manual conversion wins!

Leave a Reply

Your email address will not be published. Required fields are marked *