尝试使用len()函数从现有列表创建列表时的KeyError

时间:2012-12-15 15:03:56

标签: python dictionary while-loop

我正在尝试创建一个列表来计算每个列表列表中的价格数量。

使用以下代码:

print data['OtherBids']

我得到了以下输出:

  

[[0.074,0.073,0.072,0.03,0.029,0.024,0.021,0.02],[0.02,0.02,0.015],[0.026,0.026,0.02,0.02,0.02,0.015],[0.021,0.021,0.02] ,0.017],[0.077,0.076,0.074,0.055,0.045,0.021],[0.053,0.052,0.051,0.023,0.022],[0.016,0.016]]

基于粗略的数据视图,我们可以看到第一个列表中有8个元素,第二个列表中有3个元素,第3个列表中有6个,依此类推......但是,当我尝试使用while循环生成数据时,它返回以下错误:

data['number'][a] = len(data['OtherBids'][a])
KeyError: 'number'

导致上述错误的代码是:

a = 0
b = len(data['OtherBids'])

while a <= b - 1:
    for i in data['OtherBids']:
        data['number'][a] = len(data['OtherBids'][a]).get
    a = a + 1

有人知道我应该怎么解决它吗?

1 个答案:

答案 0 :(得分:2)

您的data没有"number"键:

a = 0
b = len(data['OtherBids'])
# add this line
data['number'] = dict()

while a <= b - 1:
    for i in data['OtherBids']:
        # seems to be mistype: len(data['OtherBids'][a]).get
        # I removed .get
        data['number'][a] = len(data['OtherBids'][a])
    a = a + 1

<强> UPD

我发现你的代码太复杂了

更多pythonic版本:

data['number'] = {}
for i, item in enumerate(data['OtherBids']):
    data['number'][i] = len(item)

内联版本:

data['number'] = {i:len(item) for i,item in enumerate(data['OtherBids'])}