Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I generate yaml file via python code?

I need to generate a yaml file and want to use python to do that. This (How can I write data in YAML format in a file?) helped me a lot but I am missing a few more steps.

I want to have something like this in the end:

- A: a
  B:
    C: c
    D: d
    E: e

This:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

d = {'- A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}
with open('result.yml', 'w') as yaml_file:
    yaml.dump(d, yaml_file, default_flow_style=False)

gives me this:

'- A': a
B:
  C: 'c'
  D: 'd'
  E: 'e'

I have a couple problems here.

  1. I need the dash before A, but in this way – A is in ” , next rows are not
  2. Indention is wrong. B, C, D and E need to go one indent to the right (if the ‘ in front of A goes away…) B needs to start right under A

For another step I would need some more, finally I want do have:

steps
- A: a
  B:
    C: c
    D: d
    E: e
- A: a1
  B:
    C: c1
    D: d1
    E: e1
- A: a2
  B:
    C: c2
    D: d2
    E: e2
....

Can someone help?

>Solution :

- A: designates a list, and that list contains a dict. So what you need, is a list:

d = [{'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}]
with open('result.yml', 'w') as yaml_file:
    yaml.dump(d, yaml_file, default_flow_style=False)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading