Check for YAML Key

I use PyYAML to work with YAML files. I wonder how I can correctly verify the existence of a key? In the example below, the titlekey is present only for list1. I want to handle the value of the header correctly if it exists, and ignore if it does not exist.

list1:
    title: This is the title
    active: True
list2:
    active: False
+5
source share
2 answers

Once you upload this file using PyYaml, it will have this structure:

{
'list1': {
    'title': "This is the title",
    'active': True,
    },
'list2: {
    'active': False,
    },
}

You can iterate with:

for k, v in my_yaml.iteritems():
    if 'title' in v:
        # the title is present
    else:
        # it not.
+11
source

If you use yaml.load, the result will be a dictionary, so you can use into check for a key:

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
+7
source

All Articles