Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

possible to ignore a KeyError?

I have a simple bit of code that goes into aws and grabs some data then prints it out to 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 don't have tags:

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

I'm not expecting every subnet to have tags so is there a way to simply ignore the lack of tags and just print empty or simply move on?

sorry if this sounds like a silly question, I've searched google and found some ideas but they look a little advanced for what I have.

like image 494
ben Avatar asked Jan 27 '17 15:01

ben


Video Answer


1 Answers

Yes, You can replace

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

with

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

Using get with allow you to define a default value in case Tags doesn't exist

like image 179
Maya G Avatar answered Sep 29 '22 18:09

Maya G