Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
17 changes: 17 additions & 0 deletions frontmatter/default_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
---
<BLANKLINE>
Body

This preserves key order, not the original YAML formatting or comments.
"""

FM_BOUNDARY = re.compile(r"^-{3,}\s*$", re.MULTILINE)
Expand Down
Loading