Python抱怨缺少字典值

时间:2019-03-19 18:57:21

标签: 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

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

1 个答案:

答案 0 :(得分:2)

在布尔设置中,如果 value 为true,则instance['Tags']为true,如果键存在,则为if 'Tags' in instance:。您需要使用{{1}}。