This module provides a loader and a dumper for PyYAML, enabling the preservation of key order when loading YAML files into `collections.OrderedDict` objects and managing `OrderedDict` objects when dumping to YAML. It is built upon PyYAML and is currently marked as deprecated by its maintainers in favor of `Phynix/yamlloader`.
pip install yamlordereddictloaderVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to load a YAML string into a `collections.OrderedDict` using `SafeLoader` and dump a `collections.OrderedDict` back to a YAML string using `SafeDumper`, preserving key order in both operations.
Migrate your project to use `Phynix/yamlloader`. Install it with `pip install yamlloader` and update your imports (e.g., `from yamlloader.ordereddict import CLoader, CDumper`).
Before using `yamlordereddictloader`, consider if PyYAML's native `dict` order preservation (Python 3.7+) and `sort_keys=False` for `yaml.dump` fulfill your requirements. If explicit `OrderedDict` instantiation is still desired for clarity or compatibility, continue using this library or its recommended successor.
Always use `yaml.load(..., Loader=yamlordereddictloader.SafeLoader)` when loading untrusted YAML content. Similarly, use `yaml.dump(..., Dumper=yamlordereddictloader.SafeDumper)` for dumping.
To correctly preserve order with aliases, you may need to implement a custom `flatten_mapping` method by subclassing `yamlordereddictloader.Loader` or consider structuring your YAML to avoid complex aliasing if strict order is paramount. Refer to advanced PyYAML customization for complex scenarios.
If you intend to use the C-accelerated loaders, you need to install and import from `Phynix/yamlloader` (e.g., `from yamlloader.ordereddict import CLoader`). If you are using `yamlordereddictloader`, use `Loader` or `SafeLoader` instead.
This often requires overriding the `flatten_mapping` method in a custom loader derived from `yamlordereddictloader.Loader` to precisely control how merged nodes are processed. A simpler fix might be to restructure the YAML or avoid aliases if explicit order is critical for merged blocks.
Ensure you are passing `Dumper=yamlordereddictloader.Dumper` or `Dumper=yamlordereddictloader.SafeDumper` to your `yaml.dump()` calls. Also, ensure you have `from collections import OrderedDict` for creating the objects to dump.