我有兴趣获取任意字典并将其复制到新字典中,并在此过程中对其进行变异。
我想做的一个突变是交换键和值。不幸的是,有些值本身就是字典。但是,这会产生“不可散列的类型:'dict'”错误。我真的不介意将值字符串化并为其提供 key 。但是,我希望能够做这样的事情:
for key in olddict:
if hashable(olddict[key]):
newdict[olddict[key]] = key
else
newdict[str(olddict[key])] = key
有没有一种干净的方法可以做到这一点不涉及捕获异常并解析“不可散列类型”的消息字符串?
最佳答案
从 Python 2.6 开始,您可以使用抽象基类 collections.Hashable
:
>>> import collections
>>> isinstance({}, collections.Hashable)
False
>>> isinstance(0, collections.Hashable)
True
__hash__
的文档中也简要提到了这种方法。 .
Doing so means that not only will instances of the class raise an appropriate
TypeError
when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checkingisinstance(obj, collections.Hashable)
(unlike classes which define their own__hash__()
to explicitly raiseTypeError
).
关于python - 向 "is hashable"询问 Python 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3460650/