首页 > 解决方案 > 将列表附加到字典值时出现键错误

问题描述

我有以下代码:

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. 想不通为什么。帮助?

标签: pythonpython-3.xkeyerror

解决方案


由于不熟悉您的问题域,我不明白这段代码背后的基本原理。但是,我已经通过添加打印调用来运行它以显示正在发生的事情(我向您推荐的一种有价值的调试技术),问题就在这里:

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

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

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

推荐阅读