Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a python list to simple YAML?

Tags:

python

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!

like image 970
Jasper33 Avatar asked Jan 08 '23 04:01

Jasper33


1 Answers

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
like image 152
Sebastian Stigler Avatar answered Jan 16 '23 21:01

Sebastian Stigler