TypeError:List indices must be integers or slices , not str
一个粉丝群里面的小伙伴,对复杂的字典取值时报错,他想实现打印peach
:
import json
python_str={
"season":
[
{"spring":[{"fruit":"pineapple"}]},
{"summer":[{"fruit":["watermelon","peach"]}]},
{"fall":[{"fruit": "apple"}]},
{"winter":[{"fruit": "orange"}]}
]
}
#定位数据节点
#打印字典所有key
print(python_str.keys())
#打印字典所有value
print(python_str.values())
print(python_str["season"]["spring"])
报错信息截图:
报错信息翻译:
类型错误:列表索引必须是整数或片,而不是str
观察代码代码可以发现红框那高亮说明取不到值
报错原因:代码有错取不到值
对于复杂的字典需要一层一层往下取,修改代码为:
import json
python_str={
"season":
[
{"spring":[{"fruit":"pineapple"}]},
{"summer":[{"fruit":["watermelon","peach"]}]},
{"fall":[{"fruit": "apple"}]},
{"winter":[{"fruit": "orange"}]}
]
}
print(python_str["season"][1]['summer'][0]['fruit'][1])