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

Python解析含浮点值的JSON文件时遇TypeError问题求助

Fixing "TypeError: list indices must be integers, not str" When Parsing JSON Floats in Python

Hey there! Let's break down this error you're running into and fix it up.

What's Causing This Error?

This error pops up when you try to use a string (like a JSON key) to index a list in Python. Lists only accept integer indices (0, 1, 2, etc.), so when you treat a list like it's a dictionary (which uses string keys), Python throws this TypeError.

Chances are, your JSON structure has a list where you expected a dictionary, or you're skipping a step where you need to index into a list first before accessing the key for your float value.

Example Scenario

Let's use a common case that triggers this error:

Sample JSON Data

{
  "measurements": [
    {"temperature": 22.5},
    {"temperature": 23.1}
  ]
}

Broken Code (Causes the Error)

import json

with open('sensor_data.json', 'r') as f:
    parsed_data = json.load(f)

# ❌ Wrong: Trying to use 'temperature' (a string) to index the list parsed_data['measurements']
current_temp = parsed_data['measurements']['temperature']

When you run this, you'll get exactly the error you mentioned: TypeError: list indices must be integers, not str — because parsed_data['measurements'] is a list, not a dictionary.

How to Fix It

You need to adjust your code to account for the list structure. Here are two common solutions:

  1. Access a specific item in the list (use an integer index first):

    # ✅ Correct: First index into the list (e.g., 0 for the first item), then get the float value
    current_temp = parsed_data['measurements'][0]['temperature']
    print(current_temp)  # Output: 22.5
    
  2. Loop through all items in the list (if you need every float value):

    # ✅ Correct: Iterate over the list to get each float value
    for measurement in parsed_data['measurements']:
        temp = measurement['temperature']
        print(f"Temperature reading: {temp}")
    

Troubleshooting Tips

  • Print your parsed data to inspect its structure. Use print(parsed_data) or pprint.pprint(parsed_data) (from the pprint module) to see clearly which parts are lists and which are dictionaries.
  • Trace your access path: Double-check each step when accessing the float value. For example, if you have data['a']['b']['c'], confirm that data['a'] is a dict, data['a']['b'] is a list (if you're using an integer index next), etc.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:33:47