dict中的hashable是什么意思

时间:2019-06-01 17:50:01

标签: python-3.x

为什么我不能在字典中写这个{names: heroes}{{names: heroes} for names, heroes in zip(names, heroes)}发生错误,是类型错误,内容为unhashable dict。是什么意思?

nums={{names:heroes} for names, heroes in zip(names,heroes)}
print(nums)
Traceback (most recent call last):
  File "C:/Users/ahmod/AppData/Local/Programs/Python/Python37-32/mim.py", line 7, in <module>
    nums={{names:heroes} for names, heroes in zip(names,heroes)}
  File "C:/Users/ahmod/AppData/Local/Programs/Python/Python37-32/mim.py", line 7, in <setcomp>
    nums={{names:heroes} for names, heroes in zip(names,heroes)}
TypeError: unhashable type: 'dict'

1 个答案:

答案 0 :(得分:1)

{{names: heroes} for names, heroes in zip(names, heroes)}

这是一组设定的理解-因为您使用的是{}大括号。在set中,每个元素必须是可哈希的。您正在将集合中的每个元素设置为{names: heroes}-dict。因此,您尝试制作set中的dict

但是不幸的是,在python中,dict不可散列-因为它是可变类型。

所以你不能那样做。

相反,您可以尝试直接创建字典:

{name: heroe for name, heroe in zip(names, heroes)}

只需除去多余的花括号即可。