我使用 PyYAML 来处理 YAML 文件。
我想知道如何正确检查某些 key 的存在?在下面的示例中,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.
关于python - 检查 YAML key 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9260875/