【问题标题】:Getting KeyError when trying to access key in a dictionary尝试访问字典中的键时出现 KeyError
【发布时间】:2021-07-07 16:41:41
【问题描述】:

我正在使用 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'

【问题讨论】:

  • 我认为您的字典之一没有 FromPort 键。尝试打印这个特定的所有键。如果键不存在,您还可以在打印要忽略的值之前设置条件*
  • 欢迎来到 SO。据我所知,FromPort 不存在某个特定条目。尝试在每个项目之前打印出ip 的值。
  • @BoarGules thnx 它的工作,请将其添加为答案。

标签: python amazon-web-services dictionary boto3 aws-sdk


【解决方案1】:

您的代码假设您尝试打印的条目始终在您返回的响应中。您可以像这样使代码更健壮:

替换

ip['FromPort'] 

ip.get('FromPort','((missing))')

【讨论】:

    猜你喜欢
    • 2017-01-06
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多