【问题标题】:resolve typeerror: list indices must be integers or slices, not str解决类型错误:列表索引必须是整数或切片,而不是 str
【发布时间】:2021-01-28 16:02:11
【问题描述】:

我对python很陌生,所以也许我的问题有一个简单的答案。 我已从 json 文件中导入数据,如下所示:

input:
with open('file_destination.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
print(data)

output: 
[{'Node': {'Construction': {'id': 'd9794e40-c894-5027-8576-b30a3eb3c95c'}]

我希望能够提取数据,例如id = d9794e40-c894-5027-8576-b30a3eb3c95c,但是我得到:

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    print(data['id'])
TypeError: list indices must be integers or slices, not str

谁能帮我解决这个问题?

【问题讨论】:

    标签: typeerror


    【解决方案1】:

    我已经跑了:

    t=[{'Node': {'Construction': {'id': 'd9794e40-c894-5027-8576-b30a3eb3c95c'}}}]
    print(t[0]['Node']['Construction']['id'])
    

    我得到这个输出:

    d9794e40-c894-5027-8576-b30a3eb3c95c
    

    我认为这可以解决您的问题。

    【讨论】:

    • 那也没用。我收到错误消息: Traceback(最近一次调用最后一次):文件“/main.py”,第 11 行,在 print(data[0]['id']) KeyError: 'id'
    • @cme这意味着第一个访问的对象不是'id'而是'Node',你尝试我的编辑了吗?
    猜你喜欢
    • 2019-12-26
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 2015-12-09
    相关资源
    最近更新 更多