Created
August 27, 2019 14:48
-
-
Save gene1wood/13b8d42464ca2a27565fd8818683d401 to your computer and use it in GitHub Desktop.
Add support for OrderedDict to PyYAML to avoid the "RepresenterError: cannot represent an object: OrderedDict" error
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
from collections import OrderedDict | |
import sys | |
import yaml | |
test1 = { | |
'beta': 1, | |
'alpha': 2, | |
'charlie': 3} | |
print(yaml.safe_dump(test1, default_flow_style=False)) | |
# Enable PyYAML support for OrderedDict | |
yaml.add_representer( | |
OrderedDict, | |
lambda dumper, data: dumper.represent_dict( | |
getattr(data, "viewitems" | |
if sys.version_info < (3,) else "items")()), | |
Dumper=yaml.SafeDumper) | |
test2 = OrderedDict() | |
test2['beta'] = 1 | |
test2['alpha'] = 2 | |
test2['charlie'] = 3 | |
print(yaml.safe_dump(test2, default_flow_style=False)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment