This is the next question Specifying Styles for Parts of a PyYAML Dump :
Consider the following code encoding as manually formatted YAML input. I am modifying YAML data, but would like to keep edges in single lines in a written YAML file.
import yaml st2 = yaml.load(""" edges: - [1, 2] - [2, 1, [1,0]] """) print yaml.dump(st2) class blockseq( dict ): pass def blockseq_rep(dumper, data): return dumper.represent_mapping( u'tag:yaml.org,2002:seq', data, flow_style=False ) class flowmap( dict ): pass def flowmap_rep(dumper, data): return dumper.represent_mapping( u'tag:yaml.org,2002:map', data, flow_style=True ) class blockseqtrue( dict ): pass def blockseqtrue_rep(dumper, data): return dumper.represent_mapping( u'tag:yaml.org,2002:seq', data, flow_style=True ) yaml.add_representer(blockseq, blockseq_rep) yaml.add_representer(blockseqtrue, blockseqtrue_rep) yaml.add_representer(flowmap, flowmap_rep) st2['edges'] = [ blockseqtrue(x) for x in st2['edges'] ] print yaml.dump(st2)
This script exits with the following output displaying an error message:
edges: - [1, 2] - - 2 - 1 - [1, 0] Traceback (most recent call last): File "test-yaml-rep.py", line 42, in <module> st2['edges'] = [ blockseqtrue(x) for x in st2['edges'] ] TypeError: cannot convert dictionary update sequence element
source share