2011-07-14 87 views
2

我的元組如列表作爲字典的關鍵

[([1, 2, 3, 4], 2), ([5, 6, 7], 3)] 

多個列表,我想有作爲鍵的字典(所以在我的字典中的每個鍵是一個元組列表) 。

不幸的是,根據TypeError我得到(unhashable type: list),似乎python不喜歡哈希列表。我的元組列表中的所有元素都是整數(如果這有所不同)。關於我能做什麼的任何建議?謝謝!

+0

僅供參考很容易看出爲什麼你不能使用列表作爲字典的關鍵字:如果你修改它們會怎麼樣?字典需要可散列類型作爲鍵的原因是,以便他們可以稍後識別鍵。 – katrielalex

回答

2
>>> def nested_lists_to_tuples(ls): 
    return tuple(nested_lists_to_tuples(l) if isinstance(l, (list, tuple)) else l for l in ls) 

>>> nested_lists_to_tuples([([1,2,3,4],2),([5,6,7],3)]) 
(((1, 2, 3, 4), 2), ((5, 6, 7), 3)) 

然後,只需使用該返回值作爲你的鑰匙。請注意,我就是這麼做的,所以你可以支持更加深刻元組和列表,嵌套混合像[([1,(2, [3, 4, [5, 6, (7, 8)]]), 3, 4], 2), ([5, 6, 7], 3)]

>>> nested_lists_to_tuples([([1, (2, [3, 4, [5, 6, (7, 8)]]), 3, 4], 2), ([5, 6, 7], 3)]) 
(((1, (2, (3, 4, (5, 6, (7, 8)))), 3, 4), 2), ((5, 6, 7), 3)) 

有可能是做一個簡單的方法,雖然。

+1

很優雅!謝謝! – aerain

+0

你很受歡迎。 – JAB

4

改爲使用元組。

>>> dict((tuple(x[0]), x[1]) for x in [([1,2,3,4],2),([5,6,7],3)]) 
{(5, 6, 7): 3, (1, 2, 3, 4): 2} 
+3

因爲元組是不可變的。 – Chris

+0

和不可變==可哈希 – Wilduck

+2

不幸的是,不可變並不總是等於[hashable](http://docs.python.org/reference/datamodel.html#object.__hash__)。 –

0

你應該列出轉換成元組

1

使用repr

class A: 
    pass 

import time 

# A and time as heterogenous elements, only to show the generality of my solution 

li_li = [ [([1,2,3,4],2),([5,6,7],3)] , 
      [([10,20,3],2),  ([5,6,77],3)] , 
      [([1,2,3,4],2),([5,6,time,7],3),([875,12], ['jk',78], A, (100,23),'zuum')] ] 




didi = {} 
for i,li in enumerate(li_li): 
    didi[repr(li)] = i 

print 'dictionary didi:' 
for k,v in didi.iteritems(): 
    print k,'  ',v 

print '----------------------------------' 

print didi[repr([([1+1+1+1+1+5,   200000/10000, 3],2),([5,8-2,7*11],3)  ])] 

結果

dictionary didi: 
[([1, 2, 3, 4], 2), ([5, 6, <module 'time' (built-in)>, 7], 3), ([875, 12], ['jk', 78], <class __main__.A at 0x011CFC70>, (100, 23), 'zuum')]  2 
[([1, 2, 3, 4], 2), ([5, 6, 7], 3)]  0 
[([10, 20, 3], 2), ([5, 6, 77], 3)]  1 
---------------------------------- 
1 
2

轉換您的清單,元組:

dict((tuple(a), b) for a,b in [([1,2,3,4],2),([5,6,7],3)]) 

如果您正在使用Python> = 2.7,你可以使用字典,內涵:

{tuple(a): b for a,b in [([1,2,3,4],2),([5,6,7],3)]}