使用Python获取YAML中所有具有相同名称的节点

3
如何使用Python将YAML文件中所有名称相同的节点值(例如title)获取到列表中。
name: test
article:
   title: title1
paper:
   title: title2
blog:
   title: title3

1
你有没有自己写的代码来解决这个问题? - sobolevn
你希望数据如何结构化?你想要一个包含每种类型标题的字典,像这样:{'title' : { 'article' : 'title1', 'paper' : 'title2', 'blog' : 'title3' }} - stevenviola
我只想返回['title1','title2','title3']。 - vaj oja
1个回答

2
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' )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接