Can I ignore KeyError?

I have a simple bit of code that goes to aws and captures some data and then outputs it to the console

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

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

I get an error because one or more of my subnets has no tags:

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

I don’t expect there are tags in each subnet, so is there a way to simply ignore the lack of tags and just print empty or just move on?

Sorry if this sounds like a dumb question, I searched google and found some ideas, but they look a bit advanced for what I have.

+4
source share
4 answers

,

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

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

get with ,

+7

KeyError exception:

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

Tags , "None".

+4

much better than catching an exception: use get

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

Another option:

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

Source: https://habr.com/ru/post/1668009/


All Articles