Asking “is hashable” about a Python value

Each Answer to this Q is separated by one/two green lines.

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
    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)
>>> isinstance(0, collections.Hashable)

This approach is also mentioned briefly in the documentation for __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).

def hashable(v):
    """Determine whether `v` can be hashed."""
    except TypeError:
        return False
    return True

All hashable built in python objects have a .__hash__() method. You can check for that.

olddict = {"a":1, "b":{"test":"dict"}, "c":"string", "d":["list"] }

for key in olddict:
      print str(olddict[key]) + " is hashable"
      print str(olddict[key]) + " is NOT hashable"


1 is hashable
string is hashable
{'test': 'dict'} is NOT hashable
['list'] is NOT hashable

Why not use duck typing?

for key in olddict:
       newdict[olddict[key]] = key
   except TypeError:
       newdict[str(olddict[key])] = key

I guess the best solution is to use collections.Hashable:

import collections
if isinstance(olddict[key], collections.Hashable):
    newdict[olddict[key]] = key
    newdict[str(olddict[key])] = key

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .