字典的键必须是可哈希的。因此,list
和dict
是不合适的。
但是tuple
是可散列的,但是如果其任何元素都不是,则失败作为键。
除了捕获异常以检查容器是否适合作为键之外,还有其他方法吗?
def is_hashable(obj):
try:
hash(obj) # this will throw an exception if 'obj' is not hashable
return True
except TypeError as err:
return False
t1 = ("a", "b", "c")
is_hashable(t1) # True
t2 = ("a", {"b":2}, {"c":3})
is_hashable(t2) # False