user1643521 user1643521 - 1 year ago 113
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 Source
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}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download