Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get yaml key value in python

My yaml file is:

clusters:
    test:                           
      tag_cl: tag0
    mtest:                           
      tag_cl: tag1, tag12
    ctest3:                           
      tag_cl: tag2, tag22

I want to get value of each tag_cl. I am expecting a below output:

tag0
tag1, tag12
tag2, tage22

I tried doing:

stream = open('clusters.yml', 'r')
data = yaml.load(stream)
var = data.get('clusters').get('test').get('tag_cl')

and just wondering if there is a way to have * instead of get('test') so that I can fetch it for all.

Please help

like image 870
SJJ Avatar asked Sep 02 '26 11:09

SJJ


1 Answers

You can use a recursive generator like so:

import yaml

def find(d, tag):
    if tag in d:
        yield d[tag]
    for k, v in d.items():
        if isinstance(v, dict):
            for i in find(v, tag):
                yield i

stream = open('clusters.yml', 'r')
data = yaml.load(stream)

for val in find(data, 'tag_cl'):
    print val

This will return the values associated with all keys matching the specified tag, regardless of nesting depth (within reason).

like image 116
Apollo2020 Avatar answered Sep 04 '26 23:09

Apollo2020



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!