Skip to content
Advertisement

Getting KeyError when trying to access key in a dictionary

I’m using Boto3 of AWS to describe the security group and trying to access the FromPort key for all the security groups available in a particular region. But when I’m trying to do so it will list some of the ports and then throws the KeyError.

Code:

import boto3
    
client = boto3.client('ec2')
response = client.describe_security_groups()

for sg in response['SecurityGroups']:
    for ip in sg['IpPermissions']:
        print(ip['FromPort'])

Output:

80
5432
22
22
3622
8443
3
80
3622
8080
5432
22
8443
443
Traceback (most recent call last):
  File ".a.py", line 8, in <module>
    print(ip['FromPort'])
KeyError: 'FromPort'

Advertisement

Answer

Your code is assuming that the entry you are trying to print is always in the response you get back. You can make the code more robust like this:

Replace

ip['FromPort'] 

with

ip.get('FromPort','((missing))')
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement