You need to enable JavaScript to run this app. Python REST API报TypeError: string indices must be integers
优惠活动
大模型
产品
解决方案
定价
更多

Python REST API报TypeError: string indices must be integers

报错原因定位

TypeError: string indices must be integers 触发的核心原因有两个:

1. 遍历逻辑错位

dynamodb.Table.get_item() 是按主键查询单条记录的接口,返回的 response["Item"] 是单条记录的属性字典,结构类似:

{
  "facility_id": "xxx",
  "facility_name": "xxx",
  "created_date": "xxx"
}

你写的 for item in response["Item"]: 踩了Python的常见坑:直接遍历字典对象时,循环拿到的变量是字典的字符串类型键,不是字典本身。比如遍历上面的示例字典,循环中item的取值依次是字符串"facility_id"、"facility_name"、"created_date"。
后续执行item["facility_id"]时,相当于尝试用字符串"facility_id"作为下标取字符串的内容,而字符串仅支持整数索引取值,自然就报了“字符串索引必须是整数”的错误。

2. 代码本身的笔误冗余

  • 重复粘贴了两次result.append({"facility_id": item["facility_id"], 的开头,属于复制带来的无效代码
  • 提前赋值的item = response['Item']变量,被循环里的同名变量直接覆盖,逻辑混乱
  • 单条查询结果根本不需要循环拼接列表,这个循环结构本身就是多余的
修正后的可用代码
response = table.get_item(
    Key={'facility_id': str(facility_id)}
)
result = []
if "Item" in response.keys():
    returnvals['status'] = 1
    # 直接取字典的属性值,不需要额外循环
    item = response['Item']
    result.append({
        "facility_id": item["facility_id"],
        "facility_name": item["facility_name"],
        "display_units": item["display_units"],
        "created_by": item["created_by"],
        "created_date": item["created_date"]
    })
returnvals['params'] = result
补充提示

如果后续业务需要查询多条匹配的记录,需要把查询接口换成query/scan,这类接口返回的多条记录是存在response["Items"](注意是复数形式的键)下的列表结构,每个列表元素是单条记录的字典。这时候写for item in response["Items"]:再取属性值,才是正确的遍历逻辑。


内容的提问来源于stack exchange,提问作者Karthik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.11 06:54:05