如何高效从AWS Auto Scaling Groups响应中提取指定字段构造字典
问题描述
调用AWS SDK的client.describe_auto_scaling_groups()接口后,得到一个嵌套结构的response字典,其中AutoScalingGroups键对应一个包含2个Auto Scaling Group(ASG)字典的列表。尝试多层遍历提取AutoScalingGroupName和DesiredCapacity字段时触发AttributeError,需要一种更可靠的实现方式,最终将这两个字段构造成如下格式的目标字典:
final = { "eks-core-20221011202902697400000006-6ac1e45e-44ee-4a43-166c-12d3d432e241": "3", "eks-dip-jobs-2022101120290341260000000d-9ec1e45e-4631-847b-b82d-d42d0fc330f0": "0" }
问题分析
AttributeError大概率是因为误用点号(.)访问字典键(比如写成asg.AutoScalingGroupName),但Python字典必须用方括号(asg['AutoScalingGroupName'])访问键。另外也可能存在目标键缺失的情况,导致访问失败。
解决方案
推荐使用字典推导式实现,代码简洁高效,同时加入键存在性检查避免异常:
# 假设response是调用接口后得到的字典 asg_list = response.get('AutoScalingGroups', []) final = { asg['AutoScalingGroupName']: str(asg['DesiredCapacity']) for asg in asg_list if 'AutoScalingGroupName' in asg and 'DesiredCapacity' in asg }
说明:
- 用
response.get('AutoScalingGroups', [])替代直接索引,避免AutoScalingGroups键不存在时触发KeyError,默认返回空列表。 - 字典推导式遍历每个ASG字典,直接提取目标键值对。
- 加入
if条件过滤掉键缺失的ASG,避免访问不存在的键导致异常。 - 将
DesiredCapacity转为字符串,匹配目标字典的格式要求。
如果需要更严谨的异常处理(比如捕获单个ASG的键缺失),也可以用try-except块:
final = {} asg_list = response.get('AutoScalingGroups', []) for asg in asg_list: try: name = asg['AutoScalingGroupName'] capacity = str(asg['DesiredCapacity']) final[name] = capacity except KeyError: # 可根据需求记录日志或跳过当前ASG continue
内容的提问来源于stack exchange,提问作者Jason Stanley
相关产品推荐
相关产品推荐

