From fb8e989faa54e83d268469a7ebc6576ca63e6292 Mon Sep 17 00:00:00 2001 From: Jack Walker Date: Mon, 7 Sep 2026 20:38:55 -0400 Subject: [PATCH] Document preserving YAML key order with sort_keys=False --- README.md | 5 +++++ frontmatter/default_handlers.py | 17 +++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/README.md b/README.md index 80ec52d..a2245d1 100644 --- a/README.md +++ b/README.md @@ -132,4 +132,9 @@ Well, hello there, world. ``` +To keep YAML keys in their existing order when saving, use +`frontmatter.dumps(post, sort_keys=False)` or +`frontmatter.dump(post, f, sort_keys=False)`. New keys appear at the end. +This preserves dictionary order, not YAML comments or formatting. + For more examples, see files in the `tests/` directory. Each sample file has a corresponding `.result.json` file showing the expected parsed output. See also the `examples/` directory, which covers more ways to customize input and output. diff --git a/frontmatter/default_handlers.py b/frontmatter/default_handlers.py index 8c5d8ec..bbe926b 100644 --- a/frontmatter/default_handlers.py +++ b/frontmatter/default_handlers.py @@ -247,6 +247,23 @@ class YAMLHandler(BaseHandler): """ Load and export YAML metadata. By default, this handler uses YAML's "safe" mode, though it's possible to override that. + + YAML output sorts metadata keys by default. Pass ``sort_keys=False`` to + :py:func:`frontmatter.dumps` or :py:func:`frontmatter.dump` to retain the + dictionary's insertion order, including keys added after loading:: + + >>> post = frontmatter.loads('---\\n' 'title: Hello\\n' 'author: Ada\\n' '---\\n' 'Body') + >>> post['date'] = '2026-01-01' + >>> print(frontmatter.dumps(post, sort_keys=False)) + --- + title: Hello + author: Ada + date: '2026-01-01' + --- + + Body + + This preserves key order, not the original YAML formatting or comments. """ FM_BOUNDARY = re.compile(r"^-{3,}\s*$", re.MULTILINE)