Python从嵌套字典(JSON文件)提取数据时出现TypeError: 'int' object is not iterable错误求助
Fixing the TypeError: 'int' object is not iterable
Let's break down what's going wrong here and how to fix it:
1. Why the error occurs
Your JSON data has DC as a single integer value (4 in the example), not an iterable like a list or dictionary. When you try to loop over it with for value in daily_data['Disturbances Count'], two critical issues are at play:
- Key mismatch: Your data uses the key
DC, but your code referencesDisturbances Count(this would first throw a KeyError if not for the next issue). - Attempting to iterate over an integer: Even if you corrected the key to
DC, you can't loop over a single integer value—this is exactly what triggers theTypeError: 'int' object is not iterable.
2. Corrected code
Here's how to properly extract the DC values into your dictionary:
from datetime import datetime DC = {} for day_str, daily_data in read_content['Tracker'].items(): # Option 1: Use the raw date string as the key DC[day_str] = daily_data['DC'] # Option 2: Convert the date string to a datetime object (if needed) # date_obj = datetime.strptime(day_str, "%b %d, %Y") # DC[date_obj] = daily_data['DC']
Key fixes explained:
- Replaced
'Disturbances Count'with'DC'to match your actual JSON data structure. - Removed the unnecessary inner
forloop—sincedaily_data['DC']is a single value, you can assign it directly to yourDCdictionary. - Fixed the undefined
datetimevariable: either use the original date string (day_str) as the key, or parse it into a proper datetime object usingstrptime(uncomment those lines if you need datetime objects instead of strings).
Example output
With your sample data, the DC dict will result in:
{'Sep 30, 2021': 4}
内容的提问来源于stack exchange,提问作者Doaa A
相关产品推荐
相关产品推荐

