0

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
  • 67
  • 1
  • 2
  • 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

1 Answers1

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