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

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 references Disturbances 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 the TypeError: '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 for loop—since daily_data['DC'] is a single value, you can assign it directly to your DC dictionary.
  • Fixed the undefined datetime variable: either use the original date string (day_str) as the key, or parse it into a proper datetime object using strptime (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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 19:02:39