本文介绍了询问“是否可散列"?关于Python值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣接受一个任意的字典并将其复制到一个新的字典中,并在此过程中对其进行变异.

I am interested in taking an arbitrary dict and copying it into a new dict, mutating it along the way.

我想做的一个突变是交换键和值.不幸的是,某些价值观本身就是命令.但是,这会生成无法散列的类型:'dict'"错误.我真的不介意将值字符串化并提供它的密钥.但是,我希望能够执行以下操作:

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

是否有一种干净的方法来做到涉及捕获异常并为"unhashable type"解析消息字符串?

Is there a clean way to do this that doesn't involve trapping an exception and parsing the message string for "unhashable type" ?

推荐答案

从Python 2.6开始,您可以使用抽象基类 collections.Hashable :

Since Python 2.6 you can use the abstract base class collections.Hashable:

>>> import collections
>>> isinstance({}, collections.Hashable)
False
>>> isinstance(0, collections.Hashable)
True

__hash__ .

这篇关于询问“是否可散列"?关于Python值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 07:03