I'm using ruamel.yaml library to dump a dictionary into a yaml file. However it does not behave the way I'd like it to.
How could I get:
---
- a:
- foo: bar
- bar: foo
instead of:
a:
- foo: bar
- bar: foo
with yaml.dump()
I'm extracting the data from:
data = {
'a': [
{'foo':'bar'},
{'bar':'foo'}
]
}
Any other library with the same functionality is open for proposal.
What you are looking for is setting explicit_start = True
on the YAML
instance. In addition you need to make the top-level a list if you want - a
instead of just a
on the second line:
import sys
import ruamel.yaml
yaml_str = """\
---
-a:
-foo: bar
-bar: foo
"""
data = [{
'a': [
{'foo':'bar'},
{'bar':'foo'}
]
}]
yaml = ruamel.yaml.YAML()
yaml.explicit_start = True
yaml.dump(data, sys.stdout)
gives:
---
- a:
- foo: bar
- bar: foo
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.