原文链接: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
Python中list作字典key报错解决办法
博客指出在Python里,用list类型数据作为字典的key会提示TypeError: unhashable type: ‘list’,而tuple类型数据作字典key则不会报错。原因是list不能作为字典的key,解决办法是将list改用tuple。
16万+





