-1

I'm getting a server list from aws and print them, however sometimes I get some missing keys:

>>> servers=ec2_client.describe_instances()
>>> for r in servers['Reservations']:
...     for i in r['Instances']:
...         print(i['InstanceId'], i['PrivateIpAddress'], i['PublicIpAddress'])
...
i-x x.y.z.p x.y.z.w
i-y x.y.z.p x.y.z.w
i-t x.y.z.p x.y.z.w
i-r x.y.z.p x.y.z.w
i-e x.y.z.p x.y.z.w
i-s x.y.z.p x.y.z.w
i-e x.y.z.p x.y.z.w
i-r x.y.z.p x.y.z.w
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
KeyError: 'PublicIpAddress'

How do I print it while ignoring missing keys (in a nice way)?

Nir
  • 2,497
  • 9
  • 42
  • 71
  • 1
    if `i` is a dict, then you can do `i.get(key, default)` to avoid an error. Maybe set `default` to `"[missing IP address]"` in this case? – Green Cloak Guy Feb 08 '21 at 15:15

1 Answers1

0

You can supply default values to the keys in case the keys are missing in python:

print(i.get('InstanceId', DEFAULT_ID), i.get('PrivateIpAddress', DEFAULT_PRIVATE), i.get('PublicIpAddress', DEFAULT_IP))

Or if you want to skip the row with missing keys entirely, you can try:

for i in r['Instances']:
    try:
        print(i['InstanceId'], i['PrivateIpAddress'], i['PublicIpAddress'])
    except KeyError:
        pass
William
  • 49
  • 2