为什么我不能在字典中写这个{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'
答案 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)}
只需除去多余的花括号即可。