How can I write data in YAML format in a file?
Asked Answered
H

4

191

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?

Horseflesh answered 18/9, 2012 at 5:4 Comment(1)
See also: How can I parse a YAML file in PythonEmblazon
A
288
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}
Agnail answered 18/9, 2012 at 6:9 Comment(4)
default_flow_style=True does the opposite as stated in the answer below!Weslee
Is there a benefit of using with here as opposed to the one-liner?Fresco
@Fresco with ensures the file is closed properly when it is no longer neededRegionalism
See Munch, #52571369 import yaml; from munch import munchify; f = munchify(yaml.safe_load(…));print(f.B.C)Hennebery
B
102

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
Balls answered 13/8, 2013 at 13:41 Comment(1)
See Munch, #52571369 import yaml; from munch import munchify; f = munchify(yaml.safe_load(…));print(f.B.C)Hennebery
M
0

As of 2024, I had to use sort_keys=False to maintain the specific order in the dictionary, i.e.:

import yaml

data = {
    "mode" : 'separate-outputs',
    "parent" : 'd93fca33ec026010b521b3587beb5897dff43189a8e1b4da078846c40d680dcei0',
    "postage" : 690,
    "inscriptions" : [
        {"file": "mango.avif", "metadata": {"title": "test"}},
        {"file": "mango2.avif", "metadata": {"title": "test"}},
    ]
}

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False, sort_keys=False)

data.yml

mode: separate-outputs
parent: d93fca55ec026010b521b3587beb5897dff43189a8e1b4da078846c40d680dcei0
postage: 690
inscriptions:
- file: mango.avif
  metadata:
    title: test
- file: mango2.avif
  metadata:
    title: test
Meit answered 15/2 at 2:37 Comment(0)
L
0

At the time this question was asked in 2012, the default flow style was None but since PyYaml 5.1, it's been False, so for recent versions of PyYaml (e.g. PyYaml 6.0.1), the nested objects are written in block style by default, i.e. the following code:

import yaml
d = {'A': 'a', 'B': {'C': 'c', 'D': 'd', 'E': 'e'}}

with open('data.yaml', 'w') as f:
    yaml.dump(d, f)

would produce a file that looks like

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

Also, if you don't pass a file handle, dump() returns the data as a string, which can be written into a file as well.

s = yaml.dump(d)

with open("data.yaml", "w") as f:
    f.write(s)

which again would produce the same file as above.


default_flow_style=None lets you mix styles:

print(yaml.dump(d, default_flow_style=None))
                   
A: a
B: {C: c, D: d, E: e}

while default_flow_style=True is straight up flow style:

print(yaml.dump(d, default_flow_style=True))
                   
{A: a, B: {C: c, D: d, E: e}}

Also, if you want to see valid kwargs of dump but help(yaml.dump) is not all too helpful, try help(yaml.dump_all) instead because dump is just a wrapper for dump_all.

Lupine answered 29/3 at 18:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.