And if by chance you want it in your originally specified format, you can overload the pyyaml class structure to customize as desired:
Code:
import yaml
from yaml.emitter import Emitter
from yaml.serializer import Serializer
from yaml.representer import Representer
from yaml.resolver import Resolver
class MyRepresenter(Representer):
def represent_sequence(self, tag, sequence, flow_style=None):
value = []
node = yaml.SequenceNode(tag, value, flow_style=flow_style)
if self.alias_key is not None:
self.represented_objects[self.alias_key] = node
best_style = True
for item in sequence:
node_item = self.represent_data(item)
if not (isinstance(node_item, yaml.ScalarNode) and
not node_item.style):
best_style = False
value.append(node_item)
if best_style:
node = self.represent_data(
str(', '.join('%s' % x.value for x in value)))
if flow_style is None:
if self.default_flow_style is not None:
node.flow_style = self.default_flow_style
else:
node.flow_style = best_style
return node
class MyDumper(Emitter, Serializer, MyRepresenter, Resolver):
def __init__(self, stream,
default_style=None, default_flow_style=None,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None,
encoding=None, explicit_start=None, explicit_end=None,
version=None, tags=None):
Emitter.__init__(self, stream, canonical=canonical,
indent=indent, width=width,
allow_unicode=allow_unicode, line_break=line_break)
Serializer.__init__(self, encoding=encoding,
explicit_start=explicit_start, explicit_end=explicit_end,
version=version, tags=tags)
MyRepresenter.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self)
print yaml.dump(data, Dumper=MyDumper, default_flow_style=False)
Produces:
A:
A1: 1
A2: 2
B:
B1:
B11:
B111: 1
B112: 2
B12:
B121: 1
B122: 2
B2:
B21: 1, 2
B22: 1, 2
C: CC