Sergei Basharov
Sergei Basharov

Reputation: 53920

Check existence of YAML key

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

Upvotes: 14

Views: 38720

Answers (3)

niklucas
niklucas

Reputation: 155

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().

Upvotes: 8

PabloG
PabloG

Reputation: 26745

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

Upvotes: 15

Ned Batchelder
Ned Batchelder

Reputation: 375882

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.

Upvotes: 17

Related Questions