5

I am not at all unfamiliar with the concept of:

TypeError: unhashable type: 'OrderedDict'

But I can not understand how the following line of codes can produce such a stack-trace.

89:     @staticmethod
90:     def diff(var1, var2, path=[], level=0, curpath=[]):
...
101:        elif isinstance(var1, list) and isinstance(var2, list):
102:            l1s = set(var1)
103:            l2s = set(var2)
104:            retlist = []

  File "myFile.py", line 102, in diff
    l1s = set(var1)
TypeError: unhashable type: 'OrderedDict'

How can line 102, in the above code throw such an exception?

theAlse
  • 5,577
  • 11
  • 68
  • 110

3 Answers3

8

Some data structures (most notably dicts and sets) require objects they contain (keys in the case of dictionaries, items in the case of sets) to implement the __hash__() magic method, so that calling hash(obj) returns a value.

This is required to optimize the structure, and together with immutability to help guarantee uniqueness of contained objects.

In your case, var1 contains some object that is not hashable (it does not implement hash()). This object is an OrderedDict, which is a mutable object and is not hashable by design.

As an example of an other object type which is mutable and not hashable by design, consider list and this example:

>>> L = [1, 2, 3]
>>> set([L])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(L)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

If you're using set() to ensure uniqueness then you must go some other way, though it's not clear from your question.

Davide R.
  • 860
  • 5
  • 24
4

dict(including OrderedDict) in python are mutable containers.

If a dict was hashed, its hash value would be changed as long as you changed the dict's contents.

Yarkee
  • 9,086
  • 5
  • 28
  • 29
1

Sets in python are based on hashes. OrderedDicts are not hashable.

Tyler Eaves
  • 12,879
  • 1
  • 32
  • 39