可以忽略 KeyError 吗?

possible to ignore a KeyError?

我有一段简单的代码可以进入 aws 并获取一些数据然后将其打印到控制台

我的代码:

import boto3
from pprint import pprint

ec2 = boto3.resource('ec2')
client = boto3.client('ec2')

#This is the VPC ID and Linked Tags
for vpctags in client.describe_vpcs()['Vpcs']: 
    print("VPC ID: ", vpctags['VpcId']) 
    print("Tags: ", vpctags['Tags'])
    for subnet in client.describe_subnets()['Subnets']:
        print("Subnet ID: ", subnet['SubnetId'])
        print("Subnet ID: ", subnet['Tags'])

###############################################

我收到一条错误消息,因为我的一个或多个子网没有标签:

print("Subnet ID: ", subnet['Tags']) KeyError: 'Tags'

我不希望每个子网都有标签,所以有没有一种方法可以简单地忽略缺少标签并打印为空或继续前进?

抱歉,如果这听起来像是一个愚蠢的问题,我搜索了 google 并找到了一些想法,但它们看起来比我现有的要先进一些。

赶上 KeyError exception:

try:
    print("Tags: ", vpctags['Tags'])
except KeyError:
    print("Tags: None")

如果 Tags 键不存在,它将改为打印 "None".

是的, 您可以替换

print("Subnet ID: ", subnet['Tags'])

print("Subnet ID: ", subnet.get('Tags', ''))

使用 get with 允许您定义默认值以防标签不存在

比捕获异常好得多:使用 get

print("Tags: ", vpctags.get('Tags',"None"))

另一个选项:

if 'Tags' in subnet:
  print("Subnet ID: ", subnet['Tags'])