列表作为字典的键

时间:2011-07-14 18:41:23

标签: python

我有多个元组列表,例如

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

我希望将其作为字典的键(因此我的字典中的每个键都是元组列表)。

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

5 个答案:

答案 0 :(得分: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}

答案 1 :(得分: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))

但是,可能有一种更简单的方法可以做到这一点。

答案 2 :(得分:2)

将您的列表转换为元组:

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

如果您使用的是Python> = 2.7,则可以使用dict-comprehensions:

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

答案 3 :(得分: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

答案 4 :(得分:0)

您应该将列表转换为元组

相关问题