简体   繁体   中英

python yaml.dump format list in other YAML format

I want to dump a Python object to a YAML file like this:

a: 5
b: 6
c: 7
d: [ 1,2,3,4]

but NOT

a: 5 
b: 6
c: 7
d 
- 1
- 2
- 3
- 4

image d was a massive list, the output gets messy for humans to see.

I use: default_flow_style=False but this uses the new line list item format.

I already use a customer dumper to stop anchors.

sbarzowski's comment worked.

I have tested for python 3.9, with PyYaml 5.4.1

Use yaml.dump with default_flow_style=None , to get the desired effect.

You need to give the dictionary you are trying to dump.

yaml.dump() will Just Work depending on the dictionary you have.

%python u
first: [1, 2, 3]
second: bar

%cat u
import yaml

d = { "first" : [1,2,3], "second" : "bar" }
print (yaml.dump(d))

Is following result meeting your expectations?

>>> import yaml
>>> dct = {"a": 5, "b": 6, "c": 7, "d": range(60)}
>>> print yaml.dump(dct)
a: 5
b: 6
c: 7
d: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
  22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
  42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]

Note, that the linebreaks are added by yaml , not by me.

If you want control over how your keys are ordered and have fine control over the flow/block style of specific mapping/dict and sequence/list you should create your objects using the the specials that ruamel.yaml uses for round-tripping. And the easiest way to do that is to load the str YAML source:

import sys
import ruamel.yaml as yaml

yaml_str = """\
a: 5
b: 6
c: 7
d: [ 1,2,3,4]
"""

data = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)
print(data)
yaml.dump(data, sys.stdout, Dumper=yaml.RoundTripDumper)

gives (preserving order and flow style, but changing the spacing around the items in the sequence, which I hope is OK with you):

a: 5
b: 6
c: 7
d: [1, 2, 3, 4]

To do this from scratch:

import sys
import ruamel.yaml as yaml
from ruamel.yaml.comments import CommentedSeq, CommentedMap

cm = CommentedMap()
cm['a'] = 5
cm['b'] = 6
cm['c'] = 7
cm['d'] = cl = CommentedSeq([1, 2, 3])
cl.append(4)
cl.fa.set_flow_style()
yaml.dump(cm, sys.stdout, Dumper=yaml.RoundTripDumper)

Which gives you the exact same output as above.

The easiest way to suppress the output of aliases IMO is to use

dumper = yaml.RoundTripDumper
dumper.ignore_aliases = lambda *args : True
yaml.dump(data, sys.stdout, Dumper=dumper)

¹ Disclaimer I am the author of ruamel.yaml

用 YAML 几个小时后,我用 JSON 做了类似的事情

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM