163

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?

dreftymac
  • 29,742
  • 25
  • 114
  • 177
user1643521
  • 2,011
  • 3
  • 13
  • 6

2 Answers2

244
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}
Cornflex
  • 583
  • 4
  • 13
Matthew Trevor
  • 13,476
  • 6
  • 35
  • 49
  • 14
    default_flow_style=True does the opposite as stated in the answer below! – encc Jul 28 '14 at 13:04
  • Is there a benefit of using `with` here as opposed to the one-liner? – src Jun 19 '19 at 14:21
  • 5
    @src `with` ensures the file is closed properly when it is no longer needed – kbolino Jun 27 '19 at 19:42
  • See [Munch](https://pypi.org/project/munch/), https://stackoverflow.com/questions/52570869/load-yaml-as-nested-objects-instead-of-dictionary-in-python `import yaml; from munch import munchify; f = munchify(yaml.safe_load(…));print(f.B.C)` – Hans Ginzel Jun 21 '20 at 21:23
93

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
Anthon
  • 59,987
  • 25
  • 170
  • 228
lou
  • 1,660
  • 13
  • 12
  • See [Munch](https://pypi.org/project/munch/), https://stackoverflow.com/questions/52570869/load-yaml-as-nested-objects-instead-of-dictionary-in-python `import yaml; from munch import munchify; f = munchify(yaml.safe_load(…));print(f.B.C)` – Hans Ginzel Jun 21 '20 at 21:24