首页 > 解决方案 > 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

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

标签: python

解决方案


在布尔设置中,instance['Tags']如果值为真,则为真,而不是如果键存在。你想要if 'Tags' in instance:


推荐阅读