{"id":7875,"library":"yamlordereddictloader","title":"YAMLOrderedDictLoader","description":"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`.","status":"deprecated","version":"0.4.2","language":"en","source_language":"en","source_url":"https://github.com/fmenabe/python-yamlordereddictloader","tags":["yaml","ordereddict","pyyaml","loader","dumper","serialization","deprecated"],"install":[{"cmd":"pip install yamlordereddictloader","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Core YAML parsing and dumping functionality relies on PyYAML.","package":"PyYAML"}],"imports":[{"symbol":"Loader","correct":"from yamlordereddictloader import Loader"},{"symbol":"SafeLoader","correct":"from yamlordereddictloader import SafeLoader"},{"symbol":"Dumper","correct":"from yamlordereddictloader import Dumper"},{"note":"CLoader and CDumper are specific to `Phynix/yamlloader` for C-accelerated versions, not `yamlordereddictloader`.","wrong":"from yamlordereddictloader import CLoader","symbol":"SafeDumper","correct":"from yamlordereddictloader import SafeDumper"},{"note":"Required for creating ordered dictionaries to dump.","symbol":"OrderedDict","correct":"from collections import OrderedDict"}],"quickstart":{"code":"import yaml\nfrom collections import OrderedDict\nfrom yamlordereddictloader import SafeLoader, SafeDumper\n\n# Create a YAML string with a specific order\nordered_data_str = \"\"\"\nkey_c: 3\nkey_a: 1\nkey_b: 2\ninner_dict:\n  inner_b: 'val_b'\n  inner_a: 'val_a'\n\"\"\"\n\n# --- Loading YAML with preserved order ---\n# Using SafeLoader for security\nloaded_data = yaml.load(ordered_data_str, Loader=SafeLoader)\n\nprint(\"Loaded data (type: \", type(loaded_data), \"):\")\nfor key, value in loaded_data.items():\n    print(f\"  {key}: {value}\")\n\nassert isinstance(loaded_data, OrderedDict)\nassert list(loaded_data.keys()) == ['key_c', 'key_a', 'key_b', 'inner_dict']\nassert list(loaded_data['inner_dict'].keys()) == ['inner_b', 'inner_a']\n\nprint(\"\\n--- Dumping data with preserved order ---\")\n# Create an OrderedDict to dump\ndata_to_dump = OrderedDict([\n    ('name', 'Alice'),\n    ('age', 30),\n    ('details', OrderedDict([\n        ('city', 'New York'),\n        ('occupation', 'Engineer')\n    ]))\n])\n\n# Using SafeDumper for security and default_flow_style=False for block style\ndumped_yaml = yaml.dump(data_to_dump, Dumper=SafeDumper, default_flow_style=False)\nprint(dumped_yaml)\n\n# Verify order after dumping and re-loading (optional, for testing)\nre_loaded_data = yaml.load(dumped_yaml, Loader=SafeLoader)\nassert list(re_loaded_data.keys()) == ['name', 'age', 'details']\nassert list(re_loaded_data['details'].keys()) == ['city', 'occupation']","lang":"python","description":"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."},"warnings":[{"fix":"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`).","message":"The `yamlordereddictloader` library is officially deprecated by its maintainer. It is recommended to migrate to the `Phynix/yamlloader` project, which offers an improved version with unit tests, performance enhancements (including C-implementation access), and active development.","severity":"breaking","affected_versions":"<=0.4.2"},{"fix":"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.","message":"For Python 3.7+ and PyYAML 5.1+, standard Python dictionaries preserve insertion order by default. Additionally, PyYAML's `dump` function can accept `sort_keys=False` to prevent alphabetical sorting during dumping. This might reduce or eliminate the need for `yamlordereddictloader` in some use cases, especially for dumping. However, `yamlordereddictloader` explicitly uses `OrderedDict` for loading.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always use `yaml.load(..., Loader=yamlordereddictloader.SafeLoader)` when loading untrusted YAML content. Similarly, use `yaml.dump(..., Dumper=yamlordereddictloader.SafeDumper)` for dumping.","message":"Using `yaml.load()` without specifying `Loader=yamlordereddictloader.SafeLoader` can be a security risk. The default `yaml.UnsafeLoader` (or `yaml.FullLoader` in newer PyYAML versions) can construct arbitrary Python objects, potentially allowing an attacker to execute malicious code if they control the YAML input.","severity":"gotcha","affected_versions":"All versions"},{"fix":"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.","message":"When loading YAML with aliased objects, `yamlordereddictloader` might not preserve the mapping order as intuitively expected for merged items. Aliased objects might be placed 'too soon' in the resulting `OrderedDict`.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"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.","cause":"`CLoader` is specific to the `Phynix/yamlloader` library, not `yamlordereddictloader`.","error":"AttributeError: module 'yamlordereddictloader' has no attribute 'CLoader'"},{"fix":"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.","cause":"Complex YAML structures involving aliases and merges can cause the `OrderedDict` from `yamlordereddictloader` to not retain the exact desired insertion order for merged content.","error":"YAML mapping order not preserved when using alias and yamlordereddictloader loader"},{"fix":"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.","cause":"This error typically occurs if you try to `yaml.dump` an `OrderedDict` without using `yamlordereddictloader.Dumper` or `SafeDumper` (or a custom representer). PyYAML's default Dumper doesn't know how to represent `OrderedDict` as a standard mapping while preserving order.","error":"yaml.representer.RepresenterError: cannot represent an object: <class 'collections.OrderedDict'>"}]}