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

Support of ordered dictionary #523

Closed
DonaldWL opened this issue May 10, 2021 · 4 comments
Closed

Support of ordered dictionary #523

DonaldWL opened this issue May 10, 2021 · 4 comments

Comments

@DonaldWL
Copy link

YAML does not support

from collections import OrderedDict

This is nice because you can force the order of the data within the YAML file to make it easer for the user to read.

Program:

from collections import OrderedDict

import yaml

MyYaml = OrderedDict()
MyYaml['c'] = 130
MyYaml['a'] = 10
MyYaml['b'] = 20

with open('x.yaml', 'w') as Fh:
yaml.dump(MyYaml, Fh)

Yaml File:

!!python/object/apply:collections.OrderedDict

      • c
      • 130
      • a
      • 10
      • b
      • 20
@nitzmahone
Copy link
Member

Ordered dictionaries are the default throughout Python 3.7+ already, and enabling it on older Pythons is pretty easy by changing the default Constructor impl in your loader.

Closing this, since it'll fairly soon be the default on all supported versions of Python anyway, so not much reason to invent a special way to override beyond what already exists.

@DonaldWL
Copy link
Author

I am using python 3.9, so I really do not understand you comment. What I am trying to do is have yaml write out the data in the correct order. JSON does this. If I read in a yaml file and then write it out in json its file is in the order of the yaml file. But if I write out a new yaml file the order is what it is, but no the order that the original yaml file was in. Makes it harder for the user to modify the yaml file.

@nitzmahone
Copy link
Member

@DonaldWL Oh, you're probably running into the default sort_keys=True on dump()- we're preserving the order internally already using the Python default ordered dict, but dump also sorts keys in mappings by default. Just do yaml.dump(..., sort_keys=False) and it should use the internal order.

@braindevices
Copy link

braindevices commented Aug 15, 2024

hmm does this supposed to work at all? I get 'cannot represent an object', OrderedDict when doing safe_dump

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