7 Methods to Convert Python Arrays to YAML
This tutorial guides you through various methods to serialize Python arrays to YAML using different libraries.
We’ll use libraries such as PyYAML, ruamel.yaml, and oyaml, as well as manual methods.
Using PyYAML
To install PyYAML, use pip:
pip install pyyaml
You can use the yaml.dump
function to convert a Python array to a YAML string:
import yaml data = ['Ahmed', 'Fatma', 'Hassan', 'Mona'] yaml_str = yaml.dump(data) print(yaml_str)
Output:
- Ahmed - Fatma - Hassan - Mona
The output shows the array serialized into YAML format where each element is listed with a hyphen.
You can also serialize more complex data structures like arrays of dictionaries:
import yaml employees = [ {'name': 'Sara', 'age': 30, 'department': 'Engineering'}, {'name': 'Khaled', 'age': 28, 'department': 'Marketing'}, {'name': 'Layla', 'age': 35, 'department': 'Sales'} ] yaml_str = yaml.dump(employees) print(yaml_str)
Output:
- age: 30 department: Engineering name: Sara - age: 28 department: Marketing name: Khaled - age: 35 department: Sales name: Layla
The output displays the list of dictionaries converted into YAML.
Using ruamel.yaml
Install ruamel.yaml
using pip:
pip install ruamel.yaml
To convert a Python array to YAML while preserving the order and formatting, use ruamel.yaml
:
from ruamel.yaml import YAML yaml = YAML() data = ['Ali', 'Salma', 'Youssef', 'Nadia'] with open('output.yaml', 'w') as file: yaml.dump(data, file)
Output(output.yaml):
- Ali - Salma - Youssef - Nadia
Using yaml Module with Custom Serialization
You can define custom representers to control how objects are serialized to YAML.
To serialize a custom Python class, define a representer:
import yaml class Employee: def __init__(self, name, age): self.name = name self.age = age def employee_representer(dumper, data): return dumper.represent_mapping('!Employee', {'name': data.name, 'age': data.age}) yaml.add_representer(Employee, employee_representer) employees = [Employee('Omar', 25), Employee('Hana', 27)] yaml_str = yaml.dump(employees) print(yaml_str)
Output:
- !Employee age: 25 name: Omar - !Employee age: 27 name: Hana
The output shows custom objects serialized with custom tags.
Manual Conversion
You can manually construct a YAML string from a Python array.
To manually create a YAML string from an array:
data = ['Samir', 'Dina', 'Karim'] yaml_str = '\n'.join(f'- {item}' for item in data) print(yaml_str)
Output:
- Samir - Dina - Karim
The code builds the YAML string by iterating over the array and formatting each item.
Using oyaml
Install oyaml
with pip:
pip install oyaml
Here’s how to use oyaml
to convert a dictionary with ordered data:
import oyaml as yaml from collections import OrderedDict data = OrderedDict([ ('name', 'Nour'), ('age', 22), ('city', 'Cairo') ]) yaml_str = yaml.dump(data) print(yaml_str)
Output:
name: Nour age: 22 city: Cairo
The output maintains the order of the keys as specified in the OrderedDict
.
Using json Module
You can use the json
module to convert arrays to JSON and then convert JSON to YAML.
First, convert the array to JSON:
import json data = ['Amira', 'Yassin', 'Noha'] json_str = json.dumps(data) print(json_str)
Output:
["Amira", "Yassin", "Noha"]
Then, convert the JSON string to a YAML string:
import yaml yaml_str = yaml.dump(json.loads(json_str)) print(yaml_str)
Output:
- Amira - Yassin - Noha
Using Data Classes with PyYAML
Data classes can be serialized to YAML using PyYAML with custom representers.
Define a data class and a custom representer:
import yaml from dataclasses import dataclass @dataclass class Product: name: str price: float in_stock: bool def product_representer(dumper, data): return dumper.represent_mapping('!Product', data.__dict__) yaml.add_representer(Product, product_representer) products = [ Product('Laptop', 15000.0, True), Product('Smartphone', 8000.0, False) ] yaml_str = yaml.dump(products) print(yaml_str)
Output:
- !Product in_stock: true name: Laptop price: 15000.0 - !Product in_stock: false name: Smartphone price: 8000.0
The output shows the data class instances serialized to YAML including all their attributes.
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.