Keys of dictionaries must be hashable. Therefore list
and dict
are inappropriate.
However tuple
is hashable, but fails as a key if any of its elements is not.
Is there another way than catching the exception to check if a container is suitable as a key?
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