181

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
  • 31,404
  • 26
  • 119
  • 182
user1643521
  • 2,191
  • 3
  • 14
  • 6

2 Answers2

271
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
  • 639
  • 5
  • 15
Matthew Trevor
  • 14,354
  • 6
  • 37
  • 50
  • 15
    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
  • 6
    @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
96

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
  • 69,918
  • 32
  • 186
  • 246
lou
  • 1,740
  • 1
  • 13
  • 13
  • 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