不可哈希类型:“列表”

时间:2019-04-22 08:45:11

标签: python

基本上,我首先将字典编入列表,然后从该列表中找出6个键。我还让用户输入一些值。现在,我想将键和值放回另一本字典中。

例如,我尝试将其以普通词典格式放置:

eliminate1 = {newcouple1:Couple01,newcouple2:Couple02,newcouple3:Couple03,newcouple4:Couple04}

import operator
from operator import itemgetter
eliminate1 = {newcouple1:Couple01,newcouple2:Couple02,newcouple3:Couple03,newcouple4:Couple04}
sorted_eliminate1 = sorted(eliminate1.items(), key=operator.itemgetter(1))
gone = print("These Couples have been eliminated: ",dict(sorted_eliminate[0:2]))
gone1 = dict(sorted_eliminate1[0:2])
remaining01 = print("These are the remaining couples: ",dict(sorted(eliminate1.items(), key = itemgetter(1))[2:]))
remaining1 = dict(sorted(eliminate1.items(), key = itemgetter(1))[2:])

我在运行代码时出错:

eliminate1 = {newcouple1:Couple01,newcouple2:Couple02,newcouple3:Couple03,newcouple4:Couple04}

这是错误: TypeError: unhashable type: 'list'

2 个答案:

答案 0 :(得分:0)

Lists不可哈希,因为它们是可变的。您能否想象是否将dictionary key分配给value,然后又更改了key?这将是一场噩梦。

lists转换为tuples以使其可散列

答案 1 :(得分:0)

为什么字典这么快?

因为,当您查找内容时,python不会查找对象。而是为每个对象分配一个整数(哈希值),然后搜索该整数。

但是,只有将其插入字典中时,才会发生这种情况。如果该对象的值稍后更改,则哈希值将不会更改,并且词典将无法找到该对象。

因此,您不能将可变对象放入字典中。对于列表,最简单的解决方案是将其转换为元组,例如代替

lst = [1, 2, 3]
x = { lst: "hello" }

lst  = [1, 2, 3]
x = { tuple(lst): "hello" }
相关问题