You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典操作报错‘list indices must be integers or slices, not str’如何提取spring?

解决TypeError: list indices must be integers or slices, not str问题

报错原因

你写的d['year']['season']['winter']之所以报错,核心是搞错了数据结构的类型:

  • d['year']对应的是列表(值是[{'season':...}]),列表只能用整数索引(比如[0])访问元素,不能直接用字符串'season';
  • 修改变量名完全没用,问题出在嵌套结构的访问方式上,和变量名无关。

正确取出'spring'的方法

按照你的原始数据结构,需要逐层拆解嵌套的列表和字典:

d = {'year':[{'season':['winter',['spring']]}]}
# 逐层访问:
# 1. 取year对应的列表的第一个元素(索引0)
# 2. 取该字典里的season键对应的列表
# 3. 取这个列表的第二个元素(索引1)
# 4. 取这个子列表的第一个元素(索引0)
spring = d['year'][0]['season'][1][0]
print(spring)  # 输出: spring

优化建议(可选)

如果是你自己定义的这个数据结构,建议把嵌套结构改得更直观,避免不必要的列表嵌套:
比如把year从列表改成字典,season从列表改成字典:

d = {'year': {'season': {'winter': ['spring']}}}
# 此时取值更符合直觉:
spring = d['year']['season']['winter'][0]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 16:18:14