繁体   English   中英

Python抱怨缺少字典值

[英]Python complains of missing dictionary value

我使用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

我究竟做错了什么? 如果标签不存在,如何正确创建例外?

在布尔设置中,如果值为 true,则instance['Tags']为true,如果键存在,则为instance['Tags'] 您想if 'Tags' in instance:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM