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

后端 未结 2 531
春和景丽
春和景丽 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:34
    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 default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

    A: a
    B: {C: c, D: d, E: e}
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题