How do I convert a python list to simple YAML?

17.3k views Asked by At

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!

1

There are 1 answers

2
Sebastian Stigler On BEST ANSWER

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