KeyError: 'Load Balancer Addresses'

KeyError: 'Load Balancer Addresses'

我一直在使用 BOTO 3 来描述帐户中可用的所有负载均衡器。我使用了以下代码片段:

'elbv2=boto3.client('elbv2',aws_access_key_id=access_key_id,aws_secret_access_key=secret_key,region_name=region)
response=elbv2.describe_load_balancers()

print(response)

此处的响应存储了包含所有信息的 dict,如下所示:

{
    'LoadBalancers': [{
        'LoadBalancerArn': 'arn:aws:elasticloadbalancing:ap-south-1:407203256002:loadbalancer/net/aws-lb-02/9d4b15bfd6f579d3',
        'DNSName': 'aws-lb-02-9d4b15bfd6f579d3.elb.ap-south-1.amazonaws.com',
        'CanonicalHostedZoneId': 'ZVDDRBQ08TROA',
        'CreatedTime': datetime.datetime(2021, 3, 31, 11, 45, 6, 729000, tzinfo = tzutc()),
        'LoadBalancerName': 'aws-lb-02',
        'Scheme': 'internet-facing',
        'VpcId': 'vpc-0be01860',
        'State': {
            'Code': 'active'
        },
        'Type': 'network',
        'AvailabilityZones': [{
            'ZoneName': 'ap-south-1a',
            'SubnetId': 'subnet-ed5fb986',
            'LoadBalancerAddresses': []
        }, {
            'ZoneName': 'ap-south-1b',
            'SubnetId': 'subnet-89d285c5',
            'LoadBalancerAddresses': []
        }]]}"'

我想访问 LoadBalancerAddress ,我是这样尝试的:

LoadBalancers=response['LoadBalancers']
for i in LoadBalancers:
  AvailabilityZones=i['AvailabilityZones']
  for j in AvailabilityZones:
    LoadBalancerAddresses=i['LoadBalancerAddresses']

但是,它抛出一个错误,说 LoadBalancerAddresses 存在关键字错误,我无法理解。 请帮助我应该如何访问变量。

您将 j['LoadBalancerAddresses'] 误输入为 i['LoadBalancerAddresses']。由于 response['LoadBalancers'] 下没有名为 LoadBalancerAddresses 的键,您的程序会抛出 KeyError.

固定版本:

LoadBalancers=response['LoadBalancers']
for i in LoadBalancers:
  AvailabilityZones=i['AvailabilityZones']
  for j in AvailabilityZones:
    LoadBalancerAddresses=j['LoadBalancerAddresses']

作为安全选项,最好在访问之前检查密钥是否存在,例如:

for j in AvailabilityZones:
    if "LoadBalancerAddresses" in j:
        LoadBalancerAddresses=j['LoadBalancerAddresses']
    else:
        print("The key does not exist")

你可以在这里使用嵌套列表理解,就像这样:

addresses = [x['LoadBalancerAddresses'] for res in aaa['LoadBalancers'] for x in res['AvailabilityZones']]

或普通嵌套列表:

addresses = []
for bal in aaa['LoadBalancers']:
    for zones in bal['AvailabilityZones']:
        addresses += zones['LoadBalancerAddresses']