Ordered YAML Loader and Dumper

1.6.0 · active · verified Thu Apr 16

yamlloader is a Python library (version 1.6.0) that provides ordered YAML loaders and dumpers for PyYAML, ensuring that the order of items in dictionaries is preserved when loading from or dumping to YAML files. It offers faster C-version implementations and automatically falls back to pure Python versions if C bindings are unavailable. The library is actively maintained, with recent updates for Python 3.14 support.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load and dump YAML content using `yamlloader`'s `CLoader` and `CDumper` to ensure dictionary order is preserved. It highlights how `yaml.load` is used with the custom loader and how the order is maintained in the resulting Python object, even for standard dictionaries in Python 3.7+.

import yaml
from yamlloader.ordereddict import CLoader, CDumper
import os

yaml_content = """
key_a: value_1
key_b: value_2
key_c: value_3
list_items:
  - item1
  - item2
  - item3
"""

# Create a dummy YAML file
with open('config.yaml', 'w') as f:
    f.write(yaml_content)

# --- Loading YAML --- 
print('--- Loading YAML ---')
with open('config.yaml', 'r') as f:
    # Using CLoader to preserve order
    data = yaml.load(f, Loader=CLoader)

print(f"Loaded data type: {type(data)}")
print(f"Loaded data: {data}")

# Verify order preservation (Python 3.7+ dicts preserve insertion order by default,
# but yamlloader explicitly guarantees and was designed around OrderedDict behavior)
expected_keys = ['key_a', 'key_b', 'key_c', 'list_items']
actual_keys = list(data.keys())
print(f"Keys in order: {actual_keys == expected_keys}")

# --- Dumping YAML --- 
print('\n--- Dumping YAML ---')
modified_data = data
modified_data['new_key'] = 'new_value'

output_yaml = yaml.dump(modified_data, Dumper=CDumper, default_flow_style=False)
print(f"Dumped YAML:\n{output_yaml}")

# Clean up dummy file
os.remove('config.yaml')

view raw JSON →