如何使用Python从嵌套的yaml中搜索打印第一个键

weylhg0b  于 2023-04-22  发布在  Python
关注(0)|答案(2)|浏览(105)

我有下面嵌套的yaml文件,我只想提取NN41_R11

devices:
  NN41_R11:
    connections:
      defaults:
        a:
          ip: 
          port: 
          protocol: telnet
        class: 
    type: IOS
testbed:
  name:

我是新的yaml解析使用python,下面是代码,我试图伪代码,但其打印整个yaml文件。

import yaml
stream = open('/tmp/testbed1.yaml','r')
data = yaml.load(stream)
print data.get('devices')
57hvy0tb

57hvy0tb1#

首先,你需要将yaml文件加载到一个python嵌套的字典对象(键/值对)中。之后,你就可以用dict.get('key')方法访问字典的值了。

# Read yaml file into nested dictionary
import yaml
fileName = '/tmp/testbed1.yaml'
with open(fileName, 'r') as yamlFile:
    data = yaml.load(yamlFile)

# Get target value
target = data.get('devices').get('NN41_R11')

# Pretty print nested dictionary (or simply print)
__import__('pprint').pprint(target)
9gm1akwq

9gm1akwq2#

你可以用下面的代码来实现。

import yaml with open("sample.yaml") as stream:
     my_dict = yaml.safe_load(stream)
     print (my_dict['devices']['NN41_R11'])
     print (my_dict.get('devices').get('NN41_R11'))
     #both the lines with give the same result you can use any

类似地,在迭代键时,您可以进入另一个嵌套字段并获取值。

相关问题