1

I have below nested yaml file, I want extract only NN41_R11.

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

I am new to yaml parsing using python, below is the code which i tried to pseudo code, but its printing the entire yaml file.

import yaml
stream = open('/tmp/testbed1.yaml','r')
data = yaml.load(stream)
print data.get('devices')
Vadiraj
  • 87
  • 1
  • 3
  • 8
  • `but its printing the entire yaml file.` - It prints a *subtree* corresponded to "devices" node. If you want to get the first key of that subtree, use `list(subtree.keys())[0]` or any other receipt from that question: https://stackoverflow.com/questions/30362391/how-to-find-first-key-in-a-dictionary. Note, that YAML standard doesn't define **order** of the keys, so the first key extracted from subtree needn't to be the first key in the yaml file. However, there are some ways for remain that order: https://stackoverflow.com/questions/13297744/pyyaml-control-ordering-of-items-called-by-yaml-load – Tsyvarev Feb 22 '18 at 15:57

2 Answers2

0

First you need to load the yaml file into a python nested dictionary object (key/value pairs). After this you're able to access the values of the dictionary with the dict.get('key') method.

# 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)
Mike Boiko
  • 11
  • 2
0

You can achieve this with below code.

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

Similarly while iterating the keys you can get into another nested field and get the value. enter image description here

Aditya Malviya
  • 1,907
  • 1
  • 20
  • 25