2013-07-15 54 views
0

我在設置索引時遇到問題。 這裏是一個例子。在字典中設置索引Python

>>> somelist = ['A', 'B', 'C', 'A', 'B'] 
>>> {x:y for x,y in enumerate(somelist)} 

{0: 'A', 1: 'B', 2: 'C', 3: 'A', 4: 'B'} 

什麼其實我想是這樣的:

{{0}: 'A', {1}: 'B', {2}: 'C', {3}: 'A', {4}: 'B'} 

我試過{{x}:y for x,y in enumerate(somelist)}但它不工作。

類型錯誤:unhashable類型: '設置'

得到任何幫助。謝謝

+0

當你聲明某些東西不是我的rk,*包含錯誤消息*。在這種情況下,我很容易猜出哪裏出了問題,但是你不能指望每個人都一直這樣猜測。 –

+0

你不想在代碼中使用像'list'這樣的名字;它掩蓋了內置的類型。改用'lst'或'somelist'或其他。 –

回答

2

您只能使用不可變的字典鍵的值。 set()值是可變的,所以這些不能被使用:

>>> lst = ['A', 'B', 'C', 'A', 'B'] 
>>> {{x}: y for x, y in enumerate(lst)} 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 1, in <dictcomp> 
TypeError: unhashable type: 'set' 

frozenset() values使用代替:

{frozenset([x]): y for x, y in enumerate(lst)} 

演示:

>>> lst = ['A', 'B', 'C', 'A', 'B'] 
>>> {frozenset([x]): y for x, y in enumerate(lst)} 
{frozenset([4]): 'B', frozenset([2]): 'C', frozenset([3]): 'A', frozenset([0]): 'A', frozenset([1]): 'B'} 

字典鍵必須是可哈希;看到映射類型的文檔:

A dictionary’s keys are almost arbitrary values. Values that are not hashable , that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys.

hashable entry in the Python glossary

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

由於set值是可變的,它們失敗可哈希標準;任何兩個現在比較相等的集合,可以稍後改變爲不再相等,因此它們的哈希值也需要改變。由於字典和集合均依賴散列值而非更改,因此可變容器不能用作字典鍵。 (而不是)不限於可哈希對象。

如果你想創建設置而是使用一個循環:

dct = {} 
for x, y in enumerate(lst): 
    dct.setdefault(y, set()).add(x) 

或使用collections.defaultdict對象,而不是和避免.setdefault()電話:

from collections import defaultdict 
dct = defaultdict(set) 
for x, y in enumerate(lst): 
    dct[y].add(x) 

演示:

>>> lst = ['A', 'B', 'C', 'A', 'B'] 
>>> dct = {} 
>>> for x, y in enumerate(lst): 
...  dct.setdefault(y, set()).add(x) 
... 
>>> dct 
{'A': set([0, 3]), 'C': set([2]), 'B': set([1, 4])} 
>>> from collections import defaultdict 
>>> dct = defaultdict(set) 
>>> for x, y in enumerate(lst): 
...  dct[y].add(x) 
... 
>>> dct 
defaultdict(<type 'set'>, {'A': set([0, 3]), 'C': set([2]), 'B': set([1, 4])}) 
+0

但爲什麼{x:{y}對於枚舉(列表)}中的x,y可以得到結果{0:{'A'},1:{'B'},2:{'C'},3:{' A'},4:{'B'}}? –

+0

@ afternoon:這是因爲限制只適用於鍵。 –

+0

請參閱[映射類型文檔](http://docs.python.org/2/library/stdtypes.html#mapping-types-dict); *字典的鍵是幾乎任意值。不可散列的值,即包含列表,字典或其他可變類型(通過值而非對象標識進行比較)的值不能用作鍵。* –