user1643521 user1643521 - 3 months ago 17
YAML Question

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?

Answer
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=True)

The default_flow_style=True 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}
Comments