SJJ SJJ - 1 year ago 67
Python Question

Get yaml key value in python

My yaml file is:

tag_cl: tag0
tag_cl: tag1, tag12
tag_cl: tag2, tag22

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

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
so that I can fetch it for all.

Please help

Answer Source

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"]


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"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download