::: Python newbie :::
I'm doing a lambda that generates a report of the resources on an account. The report is a csv file that gets uploaded into an S3 bucket (full code at the bottom)
PROBLEM When I look for a value that doesn't exist, I get a key error. for example, on this part
table10 = []
rows10 = []
cloudfront_title = 'CloudFront description chart'
client10 = boto3.client('cloudfront')
cfs = client10.list_distributions()
for cf in cfs['DistributionList']['Items']:
rows10 = [cf['Id'], cf['DomainName']]
table10.append(rows10)
Some accounts have cloud front, but others don't . When they don't I get a key error
{
"errorMessage": "'Items'",
"errorType": "KeyError",
"stackTrace": [
" File \"/var/task/index.py\", line 133, in lambda_handler\n for cf in cfs['DistributionList']['Items']:\n"
]
}
QUESTION Is there a way to validate if the value exist, and if exists bring it, otherwise bring None/Null or something like it
-*-
NEXT PROBLEM I repeat a lot of code, like a looot. I create a table and a row for each resource and then when I do the csv file I write each chart, for example:
csvfile.write(vpc_title)
csvfile.write('\n')
writer.writerows([headers])
writer.writerows(table)
csvfile.write('\n')
csvfile.write(dns_title)
csvfile.write('\n')
writer.writerows([headers1])
writer.writerows(table1)
csvfile.write('\n')
QUESTION is there a way I can avoid repeating the same code 17 times? maybe one of those magical Python loops