我有一个大型CSV文件,其中每一行都是销售事件,以销售代表ID,月份和价值来区分。我想按月为每个代表建立累计销售量。结果如下:
repID Jan Feb Mar ...
aaa 2 5 8 ...
...
...
...
我正在使用嵌套的Dict并获得KeyError:2
这是我的代码:
Outerdict = {}
for row in readfile:
nesteddict = {}
if repID not in Outerdict:
nesteddict[month] = sales
Outerdict[repID] = nesteddict
else:
Outerdict[repID][month] += sales
键错误指向最后一行代码。不确定它是否与+ =操作数有关?
答案 0 :(得分:1)
repID
存在并不意味着month
也存在。
Outerdict = {}
for row in readfile:
repID = row['repID']
month = row['month']
if repID not in Outerdict:
Outerdict[repID] = {}
if month not in Outerdict[repID]: # This month may hasn't existed before
Outerdict[repID][month] = sales
else:
Outerdict[repID][month] += sales