2011-12-16 78 views
35

我在从另一个字典开始填充python字典时遇到了麻烦。Python字典:类型错误:不可用类型:'列表'

我们假设“source”字典有字符串作为键,并且每个值都有一个自定义对象列表。

我正在创建我的目标字典,就像我一直在创建我的“源”字典一样,它怎么可能这不起作用?

我得到

TypeError: unhashable type: 'list' 

代码:

aTargetDictionary = {} 
for aKey in aSourceDictionary: 
    aTargetDictionary[aKey] = [] 
    aTargetDictionary[aKey].extend(aSourceDictionary[aKey]) 

的错误是在这条线:aTargetDictionary[aKey] = []

+5

在我的终端上正常工作。给出一个你正在使用的** aSourceDictionary **的例子 –

回答

31

你给我的错误是由于这样的事实:在python,字典密钥必须是不可变的类型(如果密钥可以改变,将会出现问题),列表是一个可变类型。

您的错误表示您尝试使用列表作为字典键,如果您想将它们作为字典中的键,则必须将列表更改为元组

根据the python doc

The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant

+1

但是在这个例子中,键是字符串(正如提问者所说的) – 0xc0de

+3

@ 0xc0de:代码说的是某事,而错误说明了别的东西,我相信错误;) –

+0

我试过了,它工作得很好。我使用了小的变量名。 – 0xc0de

7

这的确是相当奇怪的。

如果aSourceDictionary是字典,我不相信你的代码可能会以你描述的方式失败。

这导致了两个假设:

  1. 你实际运行的代码是不等同于您的问题的代码(可能更早或更晚的版本?)

  2. aSourceDictionary是其实不是一本字典,而是一些其他的结构(例如,一个列表)。

+0

我完全同意 –

2

它工作正常:http://codepad.org/5KgO0b1G, 您aSourceDictionary变量可能具有其它数据类型比字典

aSourceDictionary = { 'abc' : [1,2,3] , 'ccd' : [4,5] } 
aTargetDictionary = {} 
for aKey in aSourceDictionary: 
     aTargetDictionary[aKey] = [] 
     aTargetDictionary[aKey].extend(aSourceDictionary[aKey]) 
print aTargetDictionary 
3

根据您的描述,事情并没有加起来。如果aSourceDictionary是字典,那么您的for循环必须正常工作。

>>> source = {'a': [1, 2], 'b': [2, 3]} 
>>> target = {} 
>>> for key in source: 
... target[key] = [] 
... target[key].extend(source[key]) 
... 
>>> target 
{'a': [1, 2], 'b': [2, 3]} 
>>>