问题描述
我有兴趣将一个任意的 dict 复制到一个新的 dict 中,并在此过程中对其进行变异.
我想做的一个变化是交换键和值.不幸的是,有些值本身就是字典.然而,这会产生一个unhashable type: 'dict'"错误.我真的不介意只是将值字符串化并给它密钥.但是,我希望能够做这样的事情:
用于 olddict 中的键:如果可哈希(olddict [key]):newdict[olddict[key]] = 键别的newdict[str(olddict[key])] = key
是否有一种干净的方法来做到这一点,不涉及捕获异常并解析不可散列类型"的消息字符串?
从 Python 2.6 开始,您可以使用抽象基类 collections.Hashable
:
这样做意味着,当程序尝试检索其哈希值时,类的实例不仅会引发适当的TypeError
,而且在检查isinstance 时,它们也会被正确识别为不可哈希(obj, collections.Hashable)
(与定义自己的 __hash__()
以显式引发 TypeError
的类不同).
I am interested in taking an arbitrary dict and copying it into a new dict, mutating it along the way.
One mutation I would like to do is swap keys and value. Unfortunately, some values are dicts in their own right. However, this generates a "unhashable type: 'dict'" error. I don't really mind just stringifying the value and giving it the key. But, I'd like to be able to do something like this:
for key in olddict:
if hashable(olddict[key]):
newdict[olddict[key]] = key
else
newdict[str(olddict[key])] = key
Is there a clean way to do this that doesn't involve trapping an exception and parsing the message string for "unhashable type" ?
Since Python 2.6 you can use the abstract base class collections.Hashable
:
>>> import collections
>>> isinstance({}, collections.Hashable)
False
>>> isinstance(0, collections.Hashable)
True
This approach is also mentioned briefly in the documentation for __hash__
.
这篇关于询问“是可哈希的"关于 Python 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!