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?
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?
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}
with
here as opposed to the one-liner? –
Fresco with
ensures the file is closed properly when it is no longer needed –
Regionalism 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
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)
mode: separate-outputs
parent: d93fca55ec026010b521b3587beb5897dff43189a8e1b4da078846c40d680dcei0
postage: 690
inscriptions:
- file: mango.avif
metadata:
title: test
- file: mango2.avif
metadata:
title: test
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
.
© 2022 - 2024 — McMap. All rights reserved.