使用+ =操作数时,python嵌套的dict获取Key错误

时间:2015-10-27 05:14:22

标签: python dictionary nested

我有一个大型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

键错误指向最后一行代码。不确定它是否与+ =操作数有关?

1 个答案:

答案 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
相关问题