将列表附加到字典值时出现键错误

时间:2018-07-31 05:21:42

标签: python python-3.x keyerror

我有以下代码:

import random

dic = {2:[],4:[]}
lis = []

# Create a random dataset of 10 lists
for number in range(0,10):
    # Each list consists of 8 random numbers ...
    lis.append(random.sample(range(0,9),8))
    # ... followed by a 2 or 4, corresponding to dic keys
    lis[-1].append(random.randint(2,4))

# Iterate through lis. Append sublists to dic values, using key per
# last item of sublist, 2 or 4. Strip the key itself.

for i in lis:
    dic[i[-1]].append(i[:-1])    # <----- getting a key error here

# End result should be dic looking like this (shortened):
# dic = {2:[[1,2,5,0,8],[0,4,2,8,3]],4:[[6,2,3,6,2],[2,2,3,1,3]]}

如注释中所示,尝试附加时出现关键错误 子列表到dic中的值。不知道为什么。帮助吗?

1 个答案:

答案 0 :(得分:1)

由于您不熟悉问题域,因此我不了解此代码的原理。但是,我已经运行了它,并添加了打印调用以显示正在发生的事情(我向您推荐了一种有价值的调试技术),问题出在这里:

lis[-1].append(random.randint(2,4))

randint(2,4)返回2到4之间的随机整数,包括3 。当后续代码达到3时,您将得到一个关键错误。相反,该行应使用类似以下内容的

lis[-1].append(random.choice((2, 4)))