列表作为字典的关键

问题描述:

我的元组如列表作为字典的关键

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

多个列表,我想有作为键的字典(所以在我的字典中的每个键是一个元组列表) 。

不幸的是,根据TypeError我得到(unhashable type: list),似乎python不喜欢哈希列表。我的元组列表中的所有元素都是整数(如果这有所不同)。关于我能做什么的任何建议?谢谢!

+0

仅供参考很容易看出为什么你不能使用列表作为字典的关键字:如果你修改它们会怎么样?字典需要可散列类型作为键的原因是,以便他们可以稍后识别键。 – katrielalex

>>> 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

改为使用元组。

>>> 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__)。 –

你应该列出转换成元组

使用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 

转换您的清单,元组:

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)]}