检查是否存在YAML密钥



我使用PyYAML处理YAML文件。我想知道如何正确地检查某个密钥的存在?在下面的示例中,title键仅用于list1。如果标题值存在,我希望正确处理它,如果不存在,则忽略它。

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

使用PyYaml加载此文件后,它将具有如下结构:

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

您可以使用进行迭代

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

如果使用yaml.load,结果是一个字典,因此可以使用in来检查是否存在密钥:

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

旧帖子,但如果它能帮助其他人-在Python3:中

if 'title' in my_yaml.keys():
        # the title is present
    else:
        # it's not.

您可以使用my_yaml.items()而不是iteritems()。您也可以使用my_yaml.values()直接查看值。

最新更新