解决 TypeError: unhashable type: 'list'

报错代码行:

    index = dictionary[words]
TypeError: unhashable type: 'list'

错误原因:
Python中不支持dict()的key为list或者dict类型,因为list()和dict()是不可哈希的。

那么哪些是可哈希的,哪些是不可哈希的?

可哈希: int, float, str, tuple
不可哈希: list, set, dict

其中list不使用hash值进行索引,因此对存储元素没有可哈希的约束;set/dict使用hash进行索引,存在存储元素可哈希的限制;dict仅对key有可哈希的限制,而对value无此要求。

>>> a = [1,2,3]
>>> b = dict()
>>> b[a] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> set(a)
{1, 2, 3}
>>> set([a])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

为什么list是不可哈希的,tuple是可哈希的?https://blog.csdn.net/lanchunhui/article/details/50955238

  1. 因为list是可变的。在它的生命周期内,可任意时间改变其元素值。
  2. 元素是否可哈希是指是否使用hash进行索引。

Extra Reference:
https://segmentfault.com/a/1190000010493234

  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值