Search code examples
pythonformattingyamlpyyaml

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


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 this?


Solution

  • 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}