Skip to content

Instantly share code, notes, and snippets.

@michaelconnor00
Created February 25, 2016 23:49
Show Gist options
  • Save michaelconnor00/c3e77363267022c7797a to your computer and use it in GitHub Desktop.
Save michaelconnor00/c3e77363267022c7797a to your computer and use it in GitHub Desktop.
YAML Orderdict representer
"""
FROM: http://blog.elsdoerfer.name/2012/07/26/make-pyyaml-output-an-ordereddict/
Make PyYAML output an OrderedDict.
It will do so fine if you use yaml.dump(), but that generates ugly,
non-standard YAML code.
To use yaml.safe_dump(), you need the following.
"""
def represent_odict(dump, tag, mapping, flow_style=None):
"""Like BaseRepresenter.represent_mapping, but does not issue the sort().
"""
value = []
node = yaml.MappingNode(tag, value, flow_style=flow_style)
if dump.alias_key is not None:
dump.represented_objects[dump.alias_key] = node
best_style = True
if hasattr(mapping, 'items'):
mapping = mapping.items()
for item_key, item_value in mapping:
node_key = dump.represent_data(item_key)
node_value = dump.represent_data(item_value)
if not (isinstance(node_key, yaml.ScalarNode) and not node_key.style):
best_style = False
if not (isinstance(node_value, yaml.ScalarNode) and not node_value.style):
best_style = False
value.append((node_key, node_value))
if flow_style is None:
if dump.default_flow_style is not None:
node.flow_style = dump.default_flow_style
else:
node.flow_style = best_style
return node
yaml.SafeDumper.add_representer(OrderedDict,
lambda dumper, value: represent_odict(dumper, u'tag:yaml.org,2002:map', value))
yaml.safe_dump(data, default_flow_style=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment