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

读取CSV文件生成月份-死亡人数统计字典时遭遇'int类型不可迭代'错误的技术问询

解决"argument of type 'int' is not iterable"错误:CSV月份死亡数字典构建问题

嘿,我一眼就揪出问题啦!你在更新字典的逻辑里犯了个小疏漏——当遇到第一个新月份时,你把整个month_killed变量直接替换成了单个整数value,而不是给字典的对应键赋值。

错误原因详解

当第一次处理某个月份(比如1月)时,key not in month_killed为真,这时候你执行了month_killed = value,直接把原本是字典的month_killed变成了整数。下一次循环时,再执行if key in month_killed,Python会尝试迭代这个整数查找键,但整数是不可迭代类型,于是就抛出了argument of type 'int' is not iterable的错误。

修正后的完整代码

只需要把错误的那一行改成给字典的键赋值即可:

from csv import DictReader
with open('Datasets/year2017.csv') as file_obj:
    file_data = DictReader(file_obj, skipinitialspace=True)
    file_list = list(file_data)

month_killed = {}
for row in file_list:
    key = row['Month']
    value = row['Killed']
    # 处理空值与类型转换
    if value != '':
        value = int(float(value))
    else:
        value = 0
    # 修正字典更新逻辑
    if key in month_killed:
        month_killed[key] += value
    else:
        month_killed[key] = value  # 给对应键赋值,而非替换整个字典

额外优化建议

  1. 无需转换为列表:DictReader本身就是可迭代对象,直接迭代它能节省内存,不用先转成list:
from csv import DictReader
month_killed = {}

with open('Datasets/year2017.csv') as file_obj:
    file_data = DictReader(file_obj, skipinitialspace=True)
    for row in file_data:
        key = row['Month']
        value = row['Killed']
        value = int(float(value)) if value.strip() else 0
        month_killed[key] = month_killed.get(key, 0) + value
  1. 使用defaultdict简化逻辑:借助collections.defaultdict可以省去判断键是否存在的步骤,代码更简洁:
from csv import DictReader
from collections import defaultdict

month_killed = defaultdict(int)

with open('Datasets/year2017.csv') as file_obj:
    file_data = DictReader(file_obj, skipinitialspace=True)
    for row in file_data:
        key = row['Month']
        value = row['Killed']
        month_killed[key] += int(float(value)) if value.strip() else 0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 12:57:40