我感兴趣的是采用任意字典并将其复制到新字典中,并一路改变它。
我想做的一项改变是交换键和值。不幸的是,有些价值观本身就是命令。但是,这会生成“不可散列类型:'dict'”错误。我真的不介意只是将值字符串化并为其提供密钥。但是,我希望能够做这样的事情:
for key in olddict:
if hashable(olddict[key]):
newdict[olddict[key]] = key
else
newdict[str(olddict[key])] = key
有没有一种干净的方法可以做到这一点doesn't涉及捕获异常并解析消息字符串以获取“不可散列类型”?
Python 3.x
Use collections.abc.Hashable https://docs.python.org/3/library/collections.abc.html#collections.abc.Hashable or typing.Hashable https://docs.python.org/3/library/typing.html#typing.Hashable.
>>> import typing
>>> isinstance({}, typing.Hashable)
False
>>> isinstance(0, typing.Hashable)
True
注意:两者是相同的,后者只是前者的别名。另请注意collections.Hashable
在 Python 3.10+ 中被删除(自 3.7 起已弃用)。
Python 2.6+(原始答案)
从Python 2.6开始你可以使用抽象基类collections.Hashable https://docs.python.org/2.7/library/collections.html#collections.Hashable:
>>> import collections
>>> isinstance({}, collections.Hashable)
False
>>> isinstance(0, collections.Hashable)
True
文档中也简要提到了这种方法__hash__ http://docs.python.org/reference/datamodel.html#object.__hash__.
这样做意味着该类的实例不仅会引发适当的TypeError
当程序尝试检索其哈希值时,但在检查时它们也会被正确识别为不可哈希isinstance(obj, collections.Hashable)
(与定义自己的类不同__hash__()
明确提出TypeError
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)