The python yaml
package (version 5.1.2) is able to load the following file correctly, even though the list is not written with leading -
xx: [x1, x2]
yy: [y1, y2, y3]
The loading code is as follows
import yaml
with open('some file') as f:
data = yaml.load(f, Loader=yaml.FullLoader)
This format is used in github actions config yaml files. For example,
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [2.7, 3.5, 3.6, 3.7, 3.8]
os: [ubuntu-16.04, ubuntu-18.04]
node: [6, 8, 10]
But when I write data
to file using yaml.dump(data, f)
, it takes the -
convention, i.e.,
xx:
- x1
- x2
yy:
- y1
- y2
- y3
Is there a way to force it into the github-actions-like format?
I was told about default_flow_style
, but it doesn't give exactly what I want.
yaml.dump({"A":[1,2,3],"B":[4,5,6]},default_flow_style=True)
The output is '{A: [1, 2, 3], B: [4, 5, 6]}\n'
As pointed out by @Tsyvarev my desired behavior can be triggered by
yaml.dump({"A":[1,2,3],"B":[4,5,6]}, default_flow_style=None)
The official documentation doesn't seem to define this None
behavior though:
By default, PyYAML chooses the style of a collection depending on whether it has nested collections. If a collection has nested collections, it will be assigned the block style. Otherwise it will have the flow style.
If you want collections to be always serialized in the block style, set the parameter
default_flow_style of dump()
toFalse
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With