【问题标题】:Adding array to dictionary TypeError: unhashable type: 'list'将数组添加到字典 TypeError: unhashable type: 'list'
【发布时间】:2014-06-11 22:41:17
【问题描述】:

我无法将数组 [3,5] 添加到字典 linedict = {}。我已经检查了Python: TypeError: unhashable type: 'list' 上提到的解决方案 但仍然出现错误(TypeError: unhashable type: 'list')

    links = [links[i:i+2] for i in range(0, len(links), 2)]

    for i in range(0, len(links), 1):
        print links[i]

        if links[i] not in linedict:#on this linme
          linedict[links[i]].append( prob) 

我想创建 [3,5] 值为 0.03 的字典。

【问题讨论】:

  • links[i] 是一个列表。
  • 对不起,我编辑忘了提及
  • 这是一个list。您不能散列 list 因为它们是可变的(因此它们的散列可能会在字典的控制之外发生变化)。您必须将其转换为 tuple
  • 我已经尝试过这个 linedict[tuple(links[i])].append(prob) 但错误仍然是 Key Error
  • 因为in 关键字也在尝试对list 进行哈希处理,因为它正在测试作为键的值是否存在。

标签: python


【解决方案1】:

您已经在打印links[i],因此您应该注意到links 列表的每个元素也是一个列表。

字典不能包含列表作为键,因为字典是基于哈希表的,列表不能进行哈希处理。不过元组可以进行散列处理,并且它们与列表非常相似,因此您可以尝试将列表转换为元组。

您也不能附加到尚不存在的东西。最直接的方法是分别处理这两种情况,假设您要捕获每个匹配项并将其添加到列表中。您还可以使用 defaultdict 来自动处理首次添加,如 cmets 中所建议的那样。

if tuple(links[i]) not in linedict:
    linedict[tuple(links[i])] = [prob]
else:
    linedict[tuple(links[i])].append(prob) 

【讨论】:

  • 我尝试了上述解决方案,但错误仍然是关键错误
  • 您可以通过在 for 循环开始时对元组进行强制转换来稍微提高效率,而不是这样做(和数组访问)两次。
  • 另外,如果lindict 还没有在键中包含列表,尝试对其执行append 将导致键错误。您必须将 linedict 设为 defaultdict(list)
  • @shanky 我进行了编辑 - 我没有立即意识到您有多个错误。
  • @Mark Ransom 感谢您的解决方案,我的代码现在运行良好
【解决方案2】:

这是使用集合中的 defaultdict 的一种更简单的方法。我还对您的代码进行了一些更改,以使其更清晰。

import collections

# use a default dict
linedict = collections.defaultdict(list)
# create your list of lists as before but convert them to tuples
links = [tuple(links[i:i+2]) for i in range(0, len(links), 2)]

# iterate over the lists directly
for link in links:
    print link
    linedict[link].append(prob)  # it's a default dict so you can append directly!

【讨论】:

    猜你喜欢
    • 2014-10-15
    • 2015-02-11
    • 1970-01-01
    • 2022-11-17
    • 2019-10-11
    • 2020-03-27
    • 2020-05-11
    • 1970-01-01
    • 2022-12-05
    相关资源
    最近更新 更多