SJJ SJJ - 6 months ago 20
Python Question

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

Answer

data is a python dictionary. You can retrieve all the data by iterating through data as a dictionary. Note that you can also access python dictionaries by using ["clusters"] instead of .get("clusters").

You would do something like:

for k, v in data["clusters"].items():
    print data["clusters"][k]["tag_cl"]

EDIT

If you want to check if there is a "tag_cl" key in the data, you can use the .has_key() method:

for k, v in data["clusters"].items():
    if data["clusters"][k].has_key("tag_cl"):
        print data["clusters"][k]["tag_cl"]