如何检查容器是否适合用作字典键?

时间:2018-11-05 06:28:56

标签: python python-3.x dictionary hash key

字典的键必须是可哈希的。因此,listdict是不合适的。

但是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

0 个答案:

没有答案