Created
January 15, 2018 10:08
-
-
Save arcaduf/8edbe5900372f0dd30aa037272dfe826 to your computer and use it in GitHub Desktop.
Python: read and dump dictionary to YAML preserving order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```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