How can I write YAML data in a file?

I need to write the following data to a yaml file using Python:

{A:a, B:{C:c, D:d, E:e}} 

those. dictionary in the dictionary. How can I achieve this?

+86
python formatting yaml pyyaml
Sep 18
source share
2 answers
 import yaml data = dict( A = 'a', B = dict( C = 'c', D = 'd', E = 'e', ) ) with open('data.yml', 'w') as outfile: yaml.dump(data, outfile, default_flow_style=False) 

The parameter default_flow_style=False necessary to create the desired format (stream style), otherwise it creates a block style for nested collections:

 A: a B: {C: c, D: d, E: e} 
+134
Sep 18
source share

Link in PyYAML documentation showing the difference for default_flow_style parameter. To write it to a file in block mode (often more readable):

 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:

 A: a B: C: c D: d E: e 
+60
Aug 13 '13 at 13:41
source share



All Articles