检查列表是否已经在python中的字典中

时间:2013-08-23 17:27:58

标签: python list dictionary

我正在尝试检查列表是否已经存在于python中的字典中。 我的代码应该生成2个随机数(r1和r2)并将它们附加到字典中的列表中,如果那些相同的2个数字尚未存在。这是代码:

main_dict = {0:[], 1:[], 2:[], 3:[], 4:[]}
for x in range(0,5):
    r1 = randint(1,5)
    r2 = randint(1,5)
    temp = [r1,r2]
    if temp not in main_dict:
        main_dict[x].append(r1)
        main_dict[x].append(r2)

所以基本上main_dict应该是这样的:{0:[2,3],1:[4,1],2:[3,3],3:[3,2],4:[5, 1]},上面的代码应该注意不要重复任何组合。

错误是“TypeError:unhashable type:'list'”,我想这是因为我不能在if旁边放一个列表,但我不知道还有什么要放,我已经尝试了所有的东西来到我的脑海里。

提前致谢:)

3 个答案:

答案 0 :(得分:4)

您遇到的问题是因为如果列表存在,您正在查找字典。有了它,您将列表与字典的键进行比较。你想要做的是:

if temp not in manin_dict.values():

答案 1 :(得分:2)

if temp not in main_dict:更改为if temp not in main_dict.values():

答案 2 :(得分:1)

无法对列表进行哈希处理,因为它可以更改。你想要的是使用元组而不是列表和一组来有效地完成,以避免重复。如果您打算更改列表,可能会有一些问题需要解决。

main_dict = dict((i,[]) for i range(0,5))
main_set = set()
for x in range(0,5):
    r1 = randint(1,5)
    r2 = randint(1,5)
    temp = (r1,r2) # This is the same as tuple([r1,r2])
    if temp not in main_set:
        main_dict[x] = temp
        main_set.add(temp)

请注意,如果您只想要一组元组,则可以避免使用字典并添加到集合中。使用集合的原因是检查元素是否在集合中是O(1),同时检查元素是否在字典值列表中是否为O(N)。不是你只注意到5个值的东西,但如果你有更多的值,那肯定是这样。