字典不允许列表作为键,但允许自定义对象作为键(考虑到对象变量可以类似于列表值进行修改)
我创建了一个自定义类 Node
并能够成功添加它的实例作为字典键。
#This code works
class Node:
def __init__(self,dataval=None):
self.val = dataval
self.nextval = None
NodeA = Node(10)
dictNodeA = {NodeA:'ten'}
#This code works
但是当我尝试将 List 添加为 Key 时,出现错误。
listA = [10]
dictListA = {listA:'ten'}
##TypeError: unhashable type: 'list'
我想了解这种差异的原因,因为对象和列表都是可变的。那么为什么它在列表的情况下不起作用但在对象的情况下起作用。
I created a custom class Node
and was able to successfully add an instance of it as dictionary Key.
#This code works
class Node:
def __init__(self,dataval=None):
self.val = dataval
self.nextval = None
NodeA = Node(10)
dictNodeA = {NodeA:'ten'}
#This code works
But when I tried adding List as Key, it gave error.
listA = [10]
dictListA = {listA:'ten'}
##TypeError: unhashable type: 'list'
I want to understand the reason for this difference, as both the object and list are mutable. So why it doesn't work in case of list but works in case of object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论