Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to preserve order when dumping? #28

Closed
pcotton-intech opened this issue Jun 8, 2023 · 4 comments
Closed

How to preserve order when dumping? #28

pcotton-intech opened this issue Jun 8, 2023 · 4 comments
Assignees

Comments

@pcotton-intech
Copy link

How to preserve order when dumping?

@pcotton-intech
Copy link
Author

In the end I just did this. Seems like a fundamental yaml limitation

    sections:
       0:
          dothis: "{pipeline.spec}/dothis.yaml"   
       1:
          dothat:
       2:
          pauseandthink:
       3:
          dosomething:
       4:
          finishup:

@childsish
Copy link
Owner

There are two answers to this:

  1. By definition, dictionaries are unordered. If you need the entries to be ordered, use a list.
  2. It is possible to sort the keys by passing the sort_keys = True parameter to the dump function.

@childsish childsish closed this as not planned Won't fix, can't repro, duplicate, stale Jun 9, 2023
@timotheecour
Copy link

timotheecour commented Apr 4, 2024

@childsish but dictionaries are insertion ordered as of Python 3.6. Using a list instead of dict is not a suitable workaround; please re-open. Most tools preserve dict orderings in python, and the ones that don't just cause friciton

@childsish
Copy link
Owner

My previous comment was misleading. You can actually provide sort_keys = False to the dump function preserve the order of keys.

The default behaviour of PyYAML is to sort the keys and there's a long discussion (yaml/pyyaml#110) about whether PyYAML should preserve the order by default or sort the keys and whether preserving the order is backwards compatibility breaking. I agree that preserving the original order is the more intuitive option and after much thinking have decided to make the switch. However, I will consider this to be backwards compatibility breaking and change the major version number to reflect this.

I just hope nobody relies on the keys being sorted on dumping... 😬 If you need your keys to be sorted, please use version 1.3.5 (4499770). Otherwise the brand new 2.0.0 will be for you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants