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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With