How can I create a yaml file from pure python?

CppLearner picture CppLearner · Feb 3, 2012 · Viewed 13.5k times · Source

Example from Using YAML with Python

Original YAML file contains this

# tree format
treeroot:
    branch1:
        name: Node 1
        branch1-1:
            name: Node 1-1
    branch2:
        name: Node 2
        branch2-1:
            name: Node 2-1

After loading the content from the file using yaml.load() , and dump it into a new YAML file, I get this instead:

# tree format
treeroot:
    branch1:
        branch1-1: {name:Node 1-1}
        name: Node 1
    branch2:
        branch2-1: {name: Node 2-1}
        name: Node 2

What is the proper way of building up a YAML file straight from pure python? I don't want to write string myself. I want to build the dictionary and list.


Partial...

dataMap = {'treeroot':
               {'branch2': 
                 {'branch1-1': 
                  {'name': 'Node 1-1'},   # should be its own level
                  'name': 'Node 1'
                 }
               }
          }

Answer

CppLearner picture CppLearner · Feb 3, 2012

OKay. I just double checked the documentation. We need this at the end of the yaml.dump(data, optional_args)

The fix is this

yaml.dump(dataMap, f, default_flow_style=False)

where dataMap is the source yaml.load() and f is the file to be written to.