Ordered YAML (oyaml)

1.1 · active · verified Sat Apr 11

oyaml is a drop-in replacement for PyYAML designed to preserve dictionary ordering during YAML loading and dumping. It supports both Python 2 and Python 3 by patching the underlying PyYAML library. The current version is 1.1, with releases occurring infrequently, primarily for compatibility updates with newer PyYAML versions or test suite improvements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import oyaml as `yaml` and use its `safe_load` and `safe_dump` functions. It shows that `oyaml` preserves the order of keys when loading from a YAML string and when dumping an `OrderedDict` to a YAML string, by default, if `sort_keys=False` is used for `safe_dump` with standard dictionaries. For Python versions < 3.7, `safe_load` will return `OrderedDict` instances. For Python 3.7+ with standard `dict`s, while `safe_load` might return a standard `dict`, its order is insertion-ordered.

import oyaml as yaml
from collections import OrderedDict

yaml_data = """
key_c: 3
key_a: 1
key_b: 2
"""

# Load YAML preserving order
loaded_dict = yaml.safe_load(yaml_data)
print(f"Loaded dictionary type: {type(loaded_dict)}")
print(f"Loaded dictionary keys order: {list(loaded_dict.keys())}")

# Dump a dictionary with explicit order
ordered_data = OrderedDict([
    ('first_key', 'value_1'),
    ('second_key', 'value_2'),
    ('third_key', 'value_3')
])
dumped_yaml = yaml.safe_dump(ordered_data, sort_keys=False)
print(f"\nDumped YAML with order preserved:\n{dumped_yaml}")

view raw JSON →