python - Python 抱怨缺少字典值
问题描述
我使用 Python 构建了一个脚本,其中列出了一个帐户中的所有 aws 实例。
该脚本有效,除非它遇到没有任何标签的实例。
我试图用这些行来解释这一点:
# Test for the existance of tags
if instance['Tags']:
tags = instance['Tags']
try:
for tag in tags:
if tag["Key"] == "Name":
name = tag["Value"]
except ValueError:
print("No tags on instance ",instance["InstanceId"])
然而错误仍然存在:
Traceback (most recent call last):
File ".\aws_ec2_list_instances.py", line 180, in <module>
loop_regions()
File ".\aws_ec2_list_instances.py", line 90, in loop_regions
if instance['Tags']:
KeyError: 'Tags'
如果我注释掉与标签有关的所有行,并为“名称”设置一个静态值,脚本就可以完美运行!但是我确实需要获取名称标签。
这是一个实例的 json 表示:ec2_instance_json
我究竟做错了什么?如果标签不存在,如何正确创建异常?
解决方案
在布尔设置中,instance['Tags']
如果值为真,则为真,而不是如果键存在。你想要if 'Tags' in instance:
。
推荐阅读
- python - 在 Sagemaker 上使用 TensorFlow 进行训练没有名为“tf_container”的模块
- typescript - 函数定义参数中的大括号是什么?
- okta - 使用 Okta 进行保险柜身份验证
- php - apache 的 CORS 问题
- ssl - 带有 https 的码头服务器
- python - 以不同方式对相似数据进行正则表达式并填充数据框
- graphql - Graphql 服务器端如何使用模式
- sql - 在 Oracle 11g SQL 中,是否有更新列的优先顺序?
- sql-server - Excel VBA 到 SQL Server 2016 连接字符串错误
- javascript - 如何在 Wordpress Rest API 中显示菜单页面子项?