14

I use PyYAML to work with YAML files. I wonder how I can properly check existence of some key? In the example below title key is present only for list1. I want to process title value properly if it exists, and ignore if it is not there.

list1:
    title: This is the title
    active: True
list2:
    active: False

3 Answers 3

17

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.
15

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
8

Old post, but in case it helps anyone else - in Python3:

if 'title' in my_yaml.keys():
        # 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().

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.