Python解析含浮点值的JSON文件时遇TypeError问题求助
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:
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.5Loop 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)orpprint.pprint(parsed_data)(from thepprintmodule) 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 thatdata['a']is a dict,data['a']['b']is a list (if you're using an integer index next), etc.
内容的提问来源于stack exchange,提问作者user9300944

