[英]Getting KeyError when trying to access key in a dictionary
我正在使用 AWS 的 Boto3 來描述安全組並嘗試訪問特定區域中可用的所有安全組的FromPort
密鑰。 但是當我嘗試這樣做時,它會列出一些端口,然后拋出KeyError
。
代碼:
import boto3
client = boto3.client('ec2')
response = client.describe_security_groups()
for sg in response['SecurityGroups']:
for ip in sg['IpPermissions']:
print(ip['FromPort'])
輸出:
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'
您的代碼假設您嘗試打印的條目始終在您返回的響應中。 您可以像這樣使代碼更健壯:
代替
ip['FromPort']
和
ip.get('FromPort','((missing))')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.