【问题标题】:python nested dict gets Key error when using += operandpython嵌套dict在使用+=操作数时出现键错误
【发布时间】:2016-01-26 09:58:45
【问题描述】:

我有一个大型 CSV 文件,其中每一行都是一个销售事件,由代表 ID、月份和销售价值区分。我想按月为每个代表建立一个累计销量。所以结果看起来像:

repID  Jan  Feb  Mar  ...
aaa    2    5    8  ... 
...
...
...

我正在使用嵌套字典并得到一个 KeyError: 2

这是我的代码:

Outerdict = {}

for row in readfile:
    nesteddict = {}
    if repID not in Outerdict:
         nesteddict[month] = sales
         Outerdict[repID] = nesteddict  
    else:
         Outerdict[repID][month] += sales

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

【问题讨论】:

  • 什么是repID变量和month变量? ?
  • 可以显示csv文件内容吗??
  • 'KeyError' 是由于字典没有键。您的“repID”或“月”变量的值未在字典中填充
  • 如果你用Outerdict.setdefault(repID, {}).setdefault(month, 0)替换中间的所有内容,你的最后一行就可以了。
  • 您似乎试图简化您的代码以发布它,但在此过程中,您对其进行了如此大的更改,您取出了原来的错误并用一堆不同的错误替换了它。这段代码只会NameError,如果定义了readfilerepIDmonthsales,则不会KeyError

标签: python dictionary nested


【解决方案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

【讨论】:

  • if repID not in Outerdict.keys() - no no no no no! keys 调用完全是多余的,在 Python 2 上,它将创建一个键列表并搜索它们一个接一个地找到repID,而不是使用快速哈希查找。另一个keys 电话也有同样的问题。使用dict.keys() 几乎从来都不是一个好主意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
  • 2017-03-01
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多