Check existence of YAML key
Once you load this file with PyYaml, it will have a structure like this:
{
'list1': {
'title': "This is the title",
'active': True,
},
'list2: {
'active': False,
},
}
You can iterate it with:
for k, v in my_yaml.iteritems():
if 'title' in v:
# the title is present
else:
# it's not.
Old post, but in case it helps anyone else - in Python3:
if 'title' in my_yaml.key():
# the title is present
else:
# it's not.
You can use my_yaml.items()
instead of iteritems()
. You can also look at values directly too with my_yaml.values()
.
If you use yaml.load
, the result is a dictionary, so you can use in
to check if a key exists:
import yaml
str_ = """
list1:
title: This is the title
active: True
list2:
active: False
"""
dict_ = yaml.load(str_)
print dict_
print "title" in dict_["list1"] #> True
print "title" in dict_["list2"] #> False