How to Convert Python Dictionary to YAML
In this tutorial, you’ll learn various methods to convert Python dictionaries to YAML.
We’ll explore popular libraries like PyYAML and ruamel.yaml, as well as alternative methods using omegaconf, json2yaml, custom serialization, and Jinja2 templates.
Using PyYAML
To convert a dictionary to YAML using PyYAML, use the dump()
function:
import yaml data = { 'name': 'Amr', 'age': 30, 'city': 'Cairo', 'hobbies': ['reading', 'swimming', 'coding'] } yaml_string = yaml.dump(data, default_flow_style=False) print(yaml_string)
Output:
age: 30 city: Cairo hobbies: - reading - swimming - coding name: Amr
The default_flow_style=False
argument ensures that the output is in block style to make it readable for nested structures.
Using ruamel.yaml
To use ruamel.yaml for converting a dictionary to YAML, create a YAML object and use its dump()
method:
from ruamel.yaml import YAML data = { 'database': { 'host': 'localhost', 'port': 5432, 'user': 'Fatma', 'password': 'secret' }, 'debug': True, 'logging': { 'level': 'INFO', 'file': '/var/log/app.log' } } yaml = YAML() with open('output.yaml', 'w') as file: yaml.dump(data, file)
Output(File content):
database: host: localhost port: 5432 user: Fatma password: secret debug: true logging: level: INFO file: /var/log/app.log
ruamel.yaml preserves the order of keys and provides more control over the output format.
Using omegaconf
To convert a dictionary to YAML using omegaconf, create an OmegaConf object and use the to_yaml()
method:
from omegaconf import OmegaConf data = { 'project': 'MyApp', 'version': '1.0.0', 'settings': { 'debug': False, 'max_connections': 100, 'timeout': 30 }, 'features': ['auth', 'api', 'notifications'] } conf = OmegaConf.create(data) yaml_string = OmegaConf.to_yaml(conf) print(yaml_string)
Output:
project: MyApp version: '1.0.0' settings: debug: false max_connections: 100 timeout: 30 features: - auth - api - notifications
omegaconf is useful when you need to work with configuration files that may be modified at runtime.
Using Custom Serialization
For more control over the YAML output, you can implement a custom serialization function:
Create a custom function to convert your dictionary to YAML format:
def dict_to_yaml(data, indent=0): yaml_str = "" for key, value in data.items(): yaml_str += " " * indent + str(key) + ": " if isinstance(value, dict): yaml_str += "\n" + dict_to_yaml(value, indent + 1) elif isinstance(value, list): yaml_str += "\n" + "".join([" " * (indent + 1) + "- " + str(item) + "\n" for item in value]) else: yaml_str += str(value) + "\n" return yaml_str data = { 'person': { 'name': 'Nour', 'age': 28, 'skills': ['Python', 'YAML', 'Docker'] }, 'company': 'TechCorp', 'position': 'Developer' } print(dict_to_yaml(data))
Output:
person: name: Nour age: 28 skills: - Python - YAML - Docker company: TechCorp position: Developer
This custom function gives you full control over the YAML formatting.
Using jinja2 Templates
For more complex YAML structures, you can use Jinja2 templates to generate YAML from your dictionary:
Create a Jinja2 template and render it with your dictionary data:
from jinja2 import Template yaml_template = """ application: name: {{ app_name }} version: {{ version }} database: host: {{ db.host }} port: {{ db.port }} username: {{ db.username }} settings: debug: {{ debug }} log_level: {{ log_level }} features: {% for feature in features %} - {{ feature }} {% endfor %} """ data = { 'app_name': 'MyAwesomeApp', 'version': '2.1.0', 'db': { 'host': 'db.example.com', 'port': 5432, 'username': 'Aisha' }, 'debug': False, 'log_level': 'INFO', 'features': ['user_management', 'reporting', 'analytics'] } template = Template(yaml_template) yaml_output = template.render(data) print(yaml_output)
Output:
application: name: MyAwesomeApp version: 2.1.0 database: host: db.example.com port: 5432 username: Aisha settings: debug: False log_level: INFO features: - user_management - reporting - analytics
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.