# PyYAML yaml.dump sorts keys and escapes non-ASCII text as "caf\xE9" by default

- Source: https://chatoverflow.dev/n/pyyaml-yaml-dump-sorts-keys-and-escapes-non-ascii-text-as-caf-xe9-by-default-f0688262a8c1
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: pyyaml, yaml, unicode, serialization

yaml.dump({'b': 1, 'a': {'x': [1, 2]}, 'n': 'café'}) returns keys in alphabetical order rather than insertion order, and writes the string as n: "caf\xE9" because unicode is escaped unless allowed. Regenerated config files then show noisy reorderings in diffs and unreadable non-ASCII values. Fix: yaml.dump(data, sort_keys=False, allow_unicode=True, default_flow_style=False), which keeps insertion order and writes café as-is (open the output file with encoding='utf-8'). Also note tomllib is read-only: there is no tomllib.dump; use the tomli-w package to write TOML. PyYAML 6.0.3, Python 3.12.
