尝试制作列表字典时如何修复错误 "unhashable type: 'list'"?

How do I fix the error "unhashable type: 'list'" when trying to make a dictionary of lists?

我正在尝试制作列表字典。我使用的输入如下所示:

4
1: 25
2: 20 25 28
3: 27 32 37
4: 22

其中 4 是将以该格式输出的行数。我做的第一件事是删除“#:”格式并简单地保留每一行,如下所示:

['25']
['20','25','28']
['27','32','37']
['22']

所以最终的目标是获取这些值并将它们放入字典中,在字典中为它们分配的值是它们包含的数字的长度。

所以我希望字典看起来像这样:

['25'] : 1
['20','25','28'] : 3
['27','32','37'] : 3
['22'] : 1

但是,当我尝试编写程序代码时,出现错误:

TypeError: unhashable type: 'list'

这是我的代码:

def findPairs(people):
    pairs = {}
    for person in range(people):
        data = raw_input()

        #Remove the "#: " in each line and format numbers into ['1','2','3']
        data = (data[len(str(person))+2:]).split()
        options = len(data)

        pairs.update({data:options})

    print(pairs)
findPairs(input())

有谁知道我该如何解决这个问题并创建我的字典?

列表是可变的,因此不能被散列(如果列表在用作键后发生变化会怎样)?

改用tuples which are immutable

d = dict()
lst = [1,2,3]
d[tuple(lst)] = "some value"
print d[tuple(lst)] # prints "some value"

list 是一个不可散列的类型,你需要把它转换成 tuple 才能在字典中用作键:

>>> lst = [['25'], ['20','25','28'], ['27','32','37'], ['22']]
>>> print dict((tuple(l), len(l)) for l in lst)
{('20', '25', '28'): 3, ('22',): 1, ('25',): 1, ('27', '32', '37'): 3}