Skip to content

Commit b8c6606

Browse files
vineethsaivsclaudep
authored andcommitted
Preserve column order in YAML export
yaml.safe_dump sorts mapping keys alphabetically by default, so YAML export reordered columns (e.g. apple, id, name, zebra) inconsistently with the CSV and JSON exports, which keep the dataset's header order. Pass sort_keys=False when dumping the dataset and databook so YAML keeps the original column order. Fixes #287 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 7503651 commit b8c6606

2 files changed

Lines changed: 20 additions & 6 deletions

File tree

src/tablib/formats/_yaml.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,20 @@ class YAMLFormat:
1414
def export_set(cls, dataset):
1515
"""Returns YAML representation of Dataset."""
1616
return yaml.safe_dump(
17-
dataset._package(), default_flow_style=None, allow_unicode=True
17+
dataset._package(),
18+
default_flow_style=None,
19+
allow_unicode=True,
20+
sort_keys=False,
1821
)
1922

2023
@classmethod
2124
def export_book(cls, databook):
2225
"""Returns YAML representation of Databook."""
2326
return yaml.safe_dump(
24-
databook._package(), default_flow_style=None, allow_unicode=True
27+
databook._package(),
28+
default_flow_style=None,
29+
allow_unicode=True,
30+
sort_keys=False,
2531
)
2632

2733
@classmethod

tests/test_tablib.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1709,14 +1709,22 @@ def test_yaml_export(self):
17091709

17101710
self.founders.append(('名字', '李', 60))
17111711
expected = """\
1712-
- {first_name: John, gpa: 90, last_name: Adams}
1713-
- {first_name: George, gpa: 67, last_name: Washington}
1714-
- {first_name: Thomas, gpa: 50, last_name: Jefferson}
1715-
- {first_name: 名字, gpa: 60, last_name: 李}
1712+
- {first_name: John, last_name: Adams, gpa: 90}
1713+
- {first_name: George, last_name: Washington, gpa: 67}
1714+
- {first_name: Thomas, last_name: Jefferson, gpa: 50}
1715+
- {first_name: 名字, last_name: 李, gpa: 60}
17161716
"""
17171717
output = self.founders.yaml
17181718
self.assertEqual(output, expected)
17191719

1720+
def test_yaml_export_preserves_column_order(self):
1721+
"""YAML export must keep the dataset's column order instead of sorting the keys
1722+
alphabetically."""
1723+
data = tablib.Dataset()
1724+
data.headers = ('name', 'id', 'zebra', 'apple')
1725+
data.append(('x', 1, 'z', 'a'))
1726+
self.assertEqual(data.yaml.strip(), '- {name: x, id: 1, zebra: z, apple: a}')
1727+
17201728
def test_yaml_load(self):
17211729
""" test issue 524: invalid format """
17221730
yaml_source = Path(__file__).parent / 'files' / 'issue_524.yaml'

0 commit comments

Comments
 (0)