Reputation: 1325
I'm getting a list of aws ec2 instances with these command:
response = ec2.describe_instances()
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
I need to see if each instance has a Private IP and a Public IP. If I use a try statement for both I get a syntax error:
try instance['PrivateIpAddress'] and instance['PublicIpAddress']:
This is the error:
File ".\aws_ec2_list_instances.py", line 26
try instance['PrivateIpAddress'] and instance['PublicIpAddress']:
^
SyntaxError: invalid syntax
If I use an if statement instead of a try, python complains that the key doesn't exist if the machine doesn't have a public ip:
if instance['PrivateIpAddress'] and instance['PublicIpAddress']:
I get this error:
Traceback (most recent call last):
File ".\aws_ec2_list_instances.py", line 26, in <module>
if instance['PrivateIpAddress'] and instance['PublicIpAddress']:
KeyError: 'PublicIpAddress'
What's the right way to go about this?
Upvotes: 0
Views: 2663
Reputation: 82899
You should check if
the key is in
the dictionary:
if 'PrivateIpAddress' in instance and 'PublicIpAddress' in instance:
Note, that this will just test whether those keys are present in the dictionary, but not if they have a meaningful value, e.g. depending on how you get your data they might be None
or empty strings ""
. Alterantively, you could also use get
to get the values, or None
if they are not present.
if instance.get('PrivateIpAddress') and instance.get('PublicIpAddress'):
Here, the values are implicitly interpreted as bool
, i.e. both None
(or not-present) and empty string values would be considered False
.
Upvotes: 2
Reputation: 774
Try
statements are used for capturing various exceptions, such as the KeyError
. You'd use them as such:
try:
if instance['PrivateIpAddress'] and instance['PublicIpAddress']:
# do something
except KeyError:
# do something else
Upvotes: 1