当前位置:网站首页>TypeError:List indices must be integers or slices , not str
TypeError:List indices must be integers or slices , not str
2022-08-05 19:50:00 【无 羡ღ】
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])
边栏推荐
猜你喜欢
随机推荐
软件测试面试(五)
C# implements the singleton pattern and implementation ideas
Binary SCA fingerprint extraction black technology: go language reverse technology
Good code in the eyes of compiler engineers (1): Loop Interchange
RAID磁盘阵列详解
Vim命令总结
How to open Credential Manager in Win11?
Score-CAM|用kernel加权解释CNN的预测结果
编译器工程师眼中的好代码(1):Loop Interchange
解决Upload to dev failed. Could not resolve file “sftp://xxx.xxx.xxx.xxx:22/“. (Request failed)
344. 反转字符串-双指针法
SQL injection basic learning
The method of connecting to the local mysql8.0.30 database in the docker container
【HMS core】【FAQ】push kit、AR Engine、广告服务、扫描服务典型问题合集2
JS高阶(一)Promise
03 数据库查询、模型查询、多库查询《ThinkPHP6 入门到电商实战》
【ML】自动编码器结合支持向量回归用于回归预测(数据+代码详细教程)
面试官:一台服务器能建立的TCP链接真的只有65535个吗?
云渲染掀起虚拟演唱会新热潮
Cookies and Sessions









