TypeError:List indices must be integers or slices , not str

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])

猜你喜欢

转载自blog.csdn.net/yuan2019035055/article/details/126149910