简体   繁体   中英

How do I convert a python list to simple YAML?

My lists are very small and I can do these by hand, but I'm looking for the right way to do this programmatically. I have this as a test:

import yaml

a = ['item 1','item 2','item 3','item 4']
yaml.dump(a)

which give me this:

'[item 1, item 2, item 3, item 4]\n'

when what I want is simple YAML output like this:

---
- item 1
- item 2
- item 3
- item 4

Would this need to be in a dict structure, with values, but somehow without keys? Not quite sure how to proceed here. Any guidance is greatly appreciated!

You have to set the following paramters to the dump function:

  • explicit_start=True for the --- at the beginning of the output.
  • default_flow_style=False to print the items separated in each line.
import yaml

a = ['item 1','item 2','item 3','item 4']
yaml.dump(a, explicit_start=True, default_flow_style=False)

will give you

'---\\n- item 1\\n- item 2\\n- item 3\\n- item 4\\n'

if you print the output, you get

---
- item 1
- item 2
- item 3
- item 4

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