【问题标题】:list indices must be integers or slices, not str python3.6列表索引必须是整数或切片,而不是 str python3.6
【发布时间】:2018-09-17 22:38:56
【问题描述】:

我有一个 python 脚本,它可以提取我拥有的所有 AWS 账户中的所有 EC2 实例 ID 和标签。我试图只解析一个键的一个值。具体来说,我只想从响应中解析Key email 的Value,但我收到错误消息:list indices must be integers or slices, not str。下面是我的代码和json 响应。

Code:

import boto3
import json

conn = boto3.resource('ec2', 
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
aws_session_token=session_token)

instances = conn.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])

for instance in instances:
    host_list = instance.id
    host_tags = instance.tags
    print(host_tags['Key']['email']['Value'])

Sample JSON:

[{
    'Key': 'gitlab',
    'Value': 'true'
  }, {
    'Key': 'portfolio',
    'Value': 'xxx'
  }, {
    'Key': 'runner-manager-name',
    'Value': 'xxxxxx'
  }, ...
]

Error:

list indices must be integers or slices, not str

【问题讨论】:

  • 尝试:email = [tag['Value'] for tag in host_tags if tag['Key'] == 'email'][0]
  • 既然它在抱怨host_tags[][][],打印出host_tags 看看它是什么格式。如果是,我怀疑是[{'Key': 'gitlab', 'Value': 'true'}, ...,那么host_tags['Key'] 是没有意义的。
  • 因为你的 json 结构看起来像这样[ { }, ...]。这表明数据以列表开头,即[ ](因此它期望数字索引),那么只有里面的值是一个字典,这里使用你的字典键索引。

标签: json amazon-web-services amazon-ec2 python-3.6 boto3


【解决方案1】:

您的问题在于以下几行:

host_tags = instance.tags
print(host_tags['Key']['email']['Value'])

这样改写:

host_tags = instance.tags
for tag in host_tags:
    print('Key: ' + tag['Key'] + ' Value: ' + tag['Value'])

instance.tags 是一个字典数组。您需要处理数组中的每个项目(标签)。然后你需要处理 dict 提取它的键/值对。

【讨论】:

  • 逻辑是有道理的。我能够让它工作。
猜你喜欢
  • 2016-05-25
  • 2017-10-09
  • 2015-12-09
  • 2021-09-01
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多