python - 向 "is hashable"询问 Python 值

标签 python hash

我有兴趣获取任意字典并将其复制到新字典中,并在此过程中对其进行变异。

我想做的一个突变是交换键和值。不幸的是,有些值本身就是字典。但是,这会产生“不可散列的类型:'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 checking isinstance(obj, collections.Hashable) (unlike classes which define their own __hash__() to explicitly raise TypeError).

关于python - 向 "is hashable"询问 Python 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3460650/

相关文章:

python - 为什么不为 "in"操作设置文字 O(1)?

python - Flask 同时验证装饰器多个字段

python - 将文件加载到 2d numpy 数组中的有效方法

python - 使用 uWSGI emperor 模式独立的 vassal 日志记录

arrays - 使用 Perl 枚举哈希数组

perl - 如何在 Perl 中使用哈希值作为子例程的参数?

perl - 维护哈希值的哈希值中的顺序,并输出为 .csv

java - Android 中提供哪些哈希算法?

perl - 键/值的分配顺序是什么?

python - 不同行的正则表达式 - python