Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python嵌套dict在使用+;=操作数_Python_Dictionary_Nested - Fatal编程技术网

python嵌套dict在使用+;=操作数

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

我有一个很大的CSV文件,其中每一行都是一个销售事件,通过销售代表ID、月份和销售价值来区分。我想每月为每个销售代表建立一个累积销售量。因此,结果如下所示:

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()
几乎从来都不是一个好主意。