可以忽略KeyError?

ben*_*ben 5 python amazon-web-services aws-sdk boto3

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

mycode的:

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'])

###############################################
Run Code Online (Sandbox Code Playgroud)

我收到错误,因为我的一个或多个子网没有标记:

print("子网ID:",子网['Tags'])KeyError:'Tags'

我不希望每个子网都有标签,所以有没有办法简单地忽略标签的缺失,只打印空或只是继续?

对不起,如果这听起来像一个愚蠢的问题,我搜索谷歌并找到了一些想法,但他们看起来有点先进我所拥有的.

小智 8

是的,你可以更换

print("Subnet ID: ", subnet['Tags'])
Run Code Online (Sandbox Code Playgroud)

print("Subnet ID: ", subnet.get('Tags', ''))
Run Code Online (Sandbox Code Playgroud)

使用get with允许您在Tags不存在的情况下定义默认值