简体   繁体   English

Python 列表索引必须是整数或切片,而不是 str

[英]Python List indices must be integers or slices, not str

Assuming my json response looks like this:假设我的 json 响应如下所示:

{
  "classifier_id" : "12345",
  "url" : "https://something.com",
  "text" : "text",
  "top_class" : "class1",
  "classes" : [ {
    "class_name" : "car",
    "confidence" : 0.9862312904583641
  }, {
    "class_name" : "bus",
    "confidence" : 0.013768709541636032
  } ]
}

with the underlying GET request being底层 GET 请求是

callIBM = requests.get(
    url="https://something.com",
    params={
        "text": update.message.text,
    },
    headers={
        "Authorization": "XXX",
    },
)

and I want to parse the result in python.我想在 python 中解析结果。

I tried:我试过了:

ibmscore1 = '{}'.format(callIBM.json()["classes"][0]["class_name"]["confidence"])
ibmscore2 = '{}'.format(callIBM.json()["classes"][1]["class_name"]["confidence"])

but it's not working.但它不起作用。 Could one kindly assist a python newby?有人可以帮助 python newby 吗?

You are trying to access confidence inside class_name but class_name is not a dictionary.您正在尝试访问class_name内部的confidence ,但class_name不是字典。

Try:尝试:

resp = callIBM.json()
class1, conf1 = resp["classes"][0]["class_name"], resp["classes"][0]["confidence"]
class2, conf2 = resp["classes"][1]["class_name"], resp["classes"][0]["confidence"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 列表索引必须是整数或切片而不是 str python - list indices must be integers or slices not str python Python3-TypeError:列表索引必须是整数或切片,而不是str-List - Python3 - TypeError: list indices must be integers or slices, not str - List 使用 Python TypeError 解析 JSON:列表索引必须是整数或切片,而不是 str - Parsing JSON with Python TypeError: list indices must be integers or slices, not str 列表索引必须是整数或切片,而不是 str 错误 Python - list indices must be integers or slices, not str error Python Python JSON TypeError 列表索引必须是整数或切片,而不是 str - Python JSON TypeError list indices must be integers or slices, not str Python 错误:列表索引必须是整数或切片,而不是 str - Python Error : list indices must be integers or slices, not str TypeError:列表索引必须是整数或切片,而不是 str 使用 Python - TypeError: list indices must be integers or slices, not str Using Python Python JSON 类型错误:列表索引必须是整数或切片,而不是字符串 - Python JSON TypeError: list indices must be integers or slices, not str Python/pyfpdf:TypeError:列表索引必须是整数或切片,而不是 str - Python/pyfpdf: TypeError: list indices must be integers or slices, not str TypeError:列表索引必须是整数或切片,而不是 Python 中的 str - TypeError: list indices must be integers or slices, not str in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM