How can I write data in YAML format in a file?

后端 未结 2 528
春和景丽
春和景丽 2020-12-12 19:44

I need to write the below data to yaml file using Python:

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

i.e., dictionary in a dictionary. How can I achieve thi

2条回答
  •  囚心锁ツ
    2020-12-12 20:42

    Link to the PyYAML documentation showing the difference for the 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)
    

    produces:

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

提交回复
热议问题