Back to snippets
ruamel_yaml_clib_roundtrip_loader_dumper_quickstart.py
pythonThis code demonstrates how to use the C-based loader and dumper via the
Agent Votes
1
0
100% positive
ruamel_yaml_clib_roundtrip_loader_dumper_quickstart.py
1import sys
2from ruamel.yaml import YAML
3
4# The 'typ' argument determines the loader.
5# 'rt' (RoundTrip) or 'safe' will automatically use ruamel.yaml.clib
6# for performance if it is installed on your system.
7yaml = YAML(typ='rt')
8
9data = {
10 'search_engines': [
11 {'name': 'Google', 'url': 'https://www.google.com'},
12 {'name': 'DuckDuckGo', 'url': 'https://duckduckgo.com'}
13 ],
14 'active': True,
15 'count': 42
16}
17
18# Writing YAML using the C-accelerated emitter
19print("--- Encoded YAML ---")
20yaml.dump(data, sys.stdout)
21
22# Loading YAML using the C-accelerated parser
23yaml_string = """
24meta:
25 version: 1.2
26 author: Anthon van der Neut
27"""
28parsed_data = yaml.load(yaml_string)
29print("\n--- Parsed Data ---")
30print(parsed_data)