检查是否存在YAML密钥

Ser*_*rov 6 python yaml

我使用PyYAML来处理YAML文件.我想知道如何才能正确检查某些键的存在?在下面的示例中,titlekey仅适用于list1.如果存在,我想正确处理标题值,如果不存在则忽略它.

list1:
    title: This is the title
    active: True
list2:
    active: False
Run Code Online (Sandbox Code Playgroud)

Ned*_*der 14

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

{
'list1': {
    'title': "This is the title",
    'active': True,
    },
'list2: {
    'active': False,
    },
}
Run Code Online (Sandbox Code Playgroud)

你可以用以下方法迭代它:

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


Pab*_*loG 8

如果使用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
Run Code Online (Sandbox Code Playgroud)


小智 8

老帖子,但以防万一它对其他人有帮助 - 在 Python3 中:

if 'title' in my_yaml.keys():
        # the title is present
    else:
        # it's not.
Run Code Online (Sandbox Code Playgroud)

您可以使用my_yaml.items()代替iteritems(). 您也可以使用 直接查看值my_yaml.values()