Search code examples
pythonyaml

Convert YAML to string in Python


I am trying to convert yaml file to a particular format. The YAML file looks like:

treeroot:
    branch1:
        name: 1
        branch1-1:
            name: 2
    branch2:
        name: 3
        branch2-1:
            name: 4

I want to take the above file as input and print output in following format:

system.treeroot.branch1.name 1
system.treeroot.branch1.branch1-1.name 2
system.treeroot.branch2.name 3
system.treeroot.branch2.branch2-1.name 4

Here is the code which I have written:

#!/usr/bin/python

import yaml
m = "system"
def main():
    yaml_data = yaml.load(open('test.yaml'))
    recurse(yaml_data)

def recurse(yaml_data):
    for k,v in yaml_data.iteritems():
        global m
        if type(v) == type({}):
            m = m + "." + k
            recurse(v)
        else:
            m = m + "." + k
            print str(m)+" "+str(v)

if __name__ == "__main__":
    main()

But the output this code is printing is something like this:

system.treeroot.branch2.branch2-1.name 4
system.treeroot.branch2.branch2-1.name.name 3
system.treeroot.branch2.branch2-1.name.name.branch1.branch1-1.name 2
system.treeroot.branch2.branch2-1.name.name.branch1.branch1-1.name.name 1

How can I solve the problem?


Solution

  • First, a note on style, it is preferable to use isinstance rather than comparing types directly, i.e. if isinstance(v, dict):.

    If you let your function take two arguments instead of trying to fiddle with the global m, you should solve your problem.

    def recurse(yaml_data, m):
        for k,v in yaml_data.iteritems():
            if isinstance(v, dict):
                # m = m + "." + k
                recurse(v, m + "." + k)
            else:
                m = m + "." + k
                print str(m)+ " " +str(v)
    
    # In [4]: recurse(yaml_data, 'system')
    # system.treeroot.branch2.branch2-1.name 4
    # system.treeroot.branch2.name 3
    # system.treeroot.branch1.branch1-1.name 2
    # system.treeroot.branch1.name 1