python嵌套dict在使用+;=操作数
我有一个很大的CSV文件,其中每一行都是一个销售事件,通过销售代表ID、月份和销售价值来区分。我想每月为每个销售代表建立一个累积销售量。因此,结果如下所示:python嵌套dict在使用+;=操作数,python,dictionary,nested,Python,Dictionary,Nested,我有一个很大的CSV文件,其中每一行都是一个销售事件,通过销售代表ID、月份和销售价值来区分。我想每月为每个销售代表建立一个累积销售量。因此,结果如下所示: repID Jan Feb Mar ... aaa 2 5 8 ... ... ... ... 我正在使用嵌套的Dict并得到一个keyrerror:2 这是我的密码: Outerdict = {} for row in readfile: nesteddict = {} if repID
repID Jan Feb Mar ...
aaa 2 5 8 ...
...
...
...
我正在使用嵌套的Dict并得到一个keyrerror:2
这是我的密码:
Outerdict = {}
for row in readfile:
nesteddict = {}
if repID not in Outerdict:
nesteddict[month] = sales
Outerdict[repID] = nesteddict
else:
Outerdict[repID][month] += sales
关键错误指向代码的最后一行。不确定它是否与+=操作数有关
repID
存在并不意味着月份也存在
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
什么是repID
变量和month
变量?你能显示csv文件的内容吗?“'KeyError'是因为字典没有密钥。”。如果你用“<代码> > OutTyDist.StEffice默认值(RePID,{}))来替换中间的所有内容,或者“默认”(月,0) >你的最后一行将工作。你似乎已经试图简化你的代码来发布它,但是在这个过程中,你改变了很多,去掉了原来的bug,换成了一堆不同的bug。此代码将只定义namererror
,如果定义了readfile
、repID
、month
、和sales
,则如果repID不在Outerdict.keys()
中,则不会定义KeyError
,如果repID不在Outerdict.keys()中,则不会!调用keys
是完全多余的,在Python2上,它将创建一个键列表并逐个搜索它们以查找repID
,而不是使用快速哈希查找。其他键
调用也存在同样的问题。使用dict.keys()
几乎从来都不是一个好主意。