检查一个密钥不存在

问题描述 投票:0回答:1

我有这样的列表,下面是示例。如何使用python在没有“隐藏”键的情况下提取数据?像第二个。

我的代码是

if tab['label'] == 'toolname' and 'hidden' not in tab :
        print(course['id'], tab['label'], tab['hidden'])

我有

KeyError:'隐藏'错误,如何编写代码以替换''隐藏'不在标签中'

[{
    'id': 'context_external_tool_35702',
    'html_url': '/courses/1242593/external_tools/35702',
    'full_url': 'https://url/courses/1242593/external_tools/35702',
    'position': 35,
    'hidden': True,
    'visibility': 'admins',
    'label': 'toolname',
    'type': 'external',
    'url': 'https://url/api/v1/courses/1242593/external_tools/sessionless_launch?id=35702&launch_type=course_navigation'
}

,

{
    'id': 'context_external_tool_35702',
    'html_url': '/courses/1235556/external_tools/35702',
    'full_url': 'https://url/courses/1235556/external_tools/35702',
    'position': 19,
    'visibility': 'admins',
    'label': 'toolname',
    'type': 'external',
    'url': 'https://url/api/v1/courses/1235556/external_tools/sessionless_launch?id=35702&launch_type=course_navigation'
}]
python key
1个回答
0
投票

你的if语句工作正常。问题是,当tab['hidden']不在'hidden'时,你打印的最后一件事是tab。只打印idlabel

print(course['id'], tab['label'])
© www.soinside.com 2019 - 2024. All rights reserved.