Search code examples
pythonyamlpyyamlruamel.yaml

How to dump only lists with flow_style with PyYaml or Ruamel.yaml


I have the following content:

data = {"values": list(range(3)),'some_key': {'value': 2, 'unit': 'm'}}

When I dump this dict to YAML using default_flow_style=True I got the following content:

>>> print(yaml.dump( data, default_flow_style=False))
some_key:
  unit: m
  value: 2
values:
- 0
- 1
- 2

>>> print(yaml.dump( data, default_flow_style=True))
{some_key: {unit: m, value: 2}, values: [0, 1, 2]}

>>> print(yaml.dump( data, default_flow_style=None))
some_key: {unit: m, value: 2}
values: [0, 1, 2]

I would like to dump this dict keep the values with flow_style (like when executing with default_flow_style=None and default_flow_style=True but keeping the behavior of some_key exactly as when using default_flow_style=False.

Is it possible to achieve this?

Using PyYAML 5.3.1


Solution

  • You cannot achieve that goal using PyYAML without changing the representer that is part of the dumper.

    In ruamel.yaml you can mark a node for dumping in flow mode, and everything "below" that will then be dumped as flow-mode as well (it has to be):

    import sys
    import ruamel.yaml
    
    def flist(x):
        retval = ruamel.yaml.comments.CommentedSeq(x)
        retval.fa.set_flow_style()  # fa -> format attribute
        return retval
    
    data = {"values": flist(range(3)),'some_key': {'value': 2, 'unit': 'm'}}
    
    yaml = ruamel.yaml.YAML()
    yaml.dump(data, sys.stdout)
    

    which gives:

    values: [0, 1, 2]
    some_key:
      value: 2
      unit: m
    

    You get the values key first, because it is first in the definition of data (assuming you are using an up-to-date Python 3)