get all nodes in YAML with same name by python

1.3k Views Asked by At

How to get all the values of the nodes with same name e.g. title defined in the YAML to a list by python.

name: test
article:
   title: title1
paper:
   title: title2
blog:
   title: title3
1

There are 1 best solutions below

0
On
import os
import yaml

# Define the recursive function
def iter( map, match ):
    output = []
    for key, value in map.iteritems():
        if type( value ) == dict:
            output += iter( value, match )
        if key == match:
            output += [ value ]

    return output

f = open( infile, 'r' )
data = yaml.load( f )
f.close()

print iter( data, 'title' )