Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arcaduf/8edbe5900372f0dd30aa037272dfe826 to your computer and use it in GitHub Desktop.
Save arcaduf/8edbe5900372f0dd30aa037272dfe826 to your computer and use it in GitHub Desktop.
Python: read and dump dictionary to YAML preserving order
```python
import collections , yaml
_mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG
def dict_representer(dumper, data):
return dumper.represent_mapping(_mapping_tag, data.iteritems())
def dict_constructor(loader, node):
return collections.OrderedDict(loader.construct_pairs(node))
yaml.add_representer( collections.OrderedDict , dict_representer )
yaml.add_constructor( _mapping_tag, dict_constructor )
with open( yaml_filein , 'r' ) as stream:
dict = yaml.load( stream )
with open( yaml_fileout , 'w' ) as outfile:
yaml.dump( dict , outfile , default_flow_style=False )
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment