Created
January 29, 2020 08:46
-
-
Save tarnacious/a7aa985e25c6e31f85db69fb8dd2ae1b to your computer and use it in GitHub Desktop.
maintain key order in pyyaml for python 2.7+
This file contains hidden or 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
import yaml | |
from collections import OrderedDict | |
class OrderedDumper(yaml.SafeDumper): | |
pass | |
def _dict_representer(dumper, data): | |
return dumper.represent_mapping( | |
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, | |
data.items()) | |
OrderedDumper.add_representer(OrderedDict, _dict_representer) | |
class OrderedLoader(yaml.SafeLoader): | |
pass | |
def construct_mapping(loader, node): | |
loader.flatten_mapping(node) | |
return OrderedDict(loader.construct_pairs(node)) | |
OrderedLoader.add_constructor( | |
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, | |
construct_mapping) | |
original = OrderedDict([ | |
('one', 1), | |
('two', 2), | |
('three', 3), | |
('four', 4), | |
('nested', OrderedDict([ | |
('one', 1), | |
('two', 2), | |
('three', 3), | |
('four', 4) | |
])) | |
]) | |
print(original) | |
content = yaml.dump(original, Dumper=OrderedDumper) | |
print(content) | |
data = yaml.load(content, Loader=OrderedLoader) | |
print(data) | |
assert original == data | |
content = yaml.dump(data, Dumper=OrderedDumper) | |
print(content) | |
This file contains hidden or 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
OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4), ('nested', OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)]))]) | |
one: 1 | |
two: 2 | |
three: 3 | |
four: 4 | |
nested: | |
one: 1 | |
two: 2 | |
three: 3 | |
four: 4 | |
OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4), ('nested', OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)]))]) | |
one: 1 | |
two: 2 | |
three: 3 | |
four: 4 | |
nested: | |
one: 1 | |
two: 2 | |
three: 3 | |
four: 4 |
This file contains hidden or 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
PyYAML==5.3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment