如何遍历Boto3返回的Python字典获取APP_NAME对应的值?
获取Boto3返回字典中指定Tag的Value
问题场景
有Boto3返回的字典响应如下:
{ 'TagDescriptions': [{ 'ResourceArn': 'arn:aws:elasticloadbalancing:eu-west-1:11111111111:loadbalancer/app/AXXX001PRO/e5ca75b7', 'Tags': [{ 'Key': 'STACK', 'Value': 'ATENEA-ELB-TWRHL6' }, { 'Key': 'APP_NAME', 'Value': 'XXX001_ATENEA' }, { 'Key': 'Environment', 'Value': 'PRO' }, { 'Key': 'NAT_PROFILE', 'Value': 'LOW' }, { 'Key': 'Name', 'Value': 'AXXX004PROBELB01' }] }], 'ResponseMetadata': { 'RequestId': 'f5fba49b', 'HTTPStatusCode': 200, 'HTTPHeaders': { 'x-amzn-requestid': 'f5fba49b', 'content-type': 'text/xml', 'content-length': '1065', 'date': 'Mon, 27 Mar 2023 16:15:01 GMT' }, 'RetryAttempts': 0 } }
需要获取Key为APP_NAME对应的Value,且不能通过标签的位置定位(标签顺序可能变化)。
可行方案
以下两种方法均不依赖标签顺序,直接通过Key匹配查找:
方法一:嵌套循环遍历
# 假设response为Boto3返回的字典 app_name = None # 遍历每个资源的标签描述 for tag_desc in response['TagDescriptions']: # 遍历当前资源的所有标签 for tag in tag_desc['Tags']: if tag['Key'] == 'APP_NAME': app_name = tag['Value'] break # 找到目标标签后退出内层循环 if app_name: break # 找到值后退出外层循环 # 输出结果 print(app_name) # 输出: XXX001_ATENEA
方法二:生成器表达式简化查找
用生成器表达式可以更简洁地实现,同时支持找不到时返回默认值(如下示例返回None):
# 生成器表达式快速匹配目标标签值 app_name = next( (tag['Value'] for tag_desc in response['TagDescriptions'] for tag in tag_desc['Tags'] if tag['Key'] == 'APP_NAME'), None ) print(app_name) # 输出: XXX001_ATENEA(未找到则输出None)
说明
- 如果
TagDescriptions中包含多个资源,上述方法会返回第一个匹配APP_NAME标签的值;若需要获取所有匹配的值,可将生成器表达式改为列表推导式:
all_app_names = [tag['Value'] for tag_desc in response['TagDescriptions'] for tag in tag_desc['Tags'] if tag['Key'] == 'APP_NAME']
内容的提问来源于stack exchange,提问作者Zeus
相关产品推荐
相关产品推荐

