Python错误集锦:list类型的数据作为字典的key提示TypeError: unhashable type: ‘list’

原文链接:http://www.juzicode.com/archives/2706

错误提示:

用tuple类型的数据作为字典的key不报错,用list类型的数据作为字典的key时,提示TypeError: unhashable type: ‘list’ 

#juzicode.com/vx:桔子code
tuple1 = (1,2,3)
tuple2 = (4,5,6)
d3 = {tuple1:10,tuple2:20} #用tuple作为字典的key
print(d3) 
list1 = [1,2,3]
list2 = [4,5,6]
d4 = {list1:10, list2:20}  #用list作为字典的key
{(1, 2, 3): 10, (4, 5, 6): 20}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-25e3bb4c9ee3> in <module>
      6 list1 = [1,2,3]
      7 list2 = [4,5,6]
----> 8 d4 = {list1:10, list2:20}  #用list作为字典的key

TypeError: unhashable type: 'list'

可能原因:

1、list不能作为字典的key。

解决方法:

1、list改用tuple

posted @ 2020-12-19 11:27  桔子code  阅读(225)  评论(0编辑  收藏  举报