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:
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.
- I need the dash before A, but in this way - A is in '' , next rows are not
- 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?
CodePudding user response:
- 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)
CodePudding user response:
Your output is a list, but you're starting with a dict.
>>> import yaml
>>> l = [{'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}]
>>> print(yaml.dump(l))
- A: a
B:
C: c
D: d
E: e