Python不可散列类型:“ OrderedDict”

the*_*lse 5 python dictionary exception

我对以下概念并不陌生:

TypeError: unhashable type: 'OrderedDict'
Run Code Online (Sandbox Code Playgroud)

但是我不明白下面的代码行如何产生这样的堆栈跟踪。

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'
Run Code Online (Sandbox Code Playgroud)

102上面的代码中的line怎么会抛出这样的异常?

Dav*_* R. 6

某些数据结构(最值得注意的是dicts和sets)需要它们包含的对象(对于字典来说是键,对于集合来说是项)实现__hash__()magic方法,以便调用hash(obj)返回值。

这是优化结构所必需的,并具有不变性以帮助保证所包含对象的唯一性。

就您而言,var1包含一些不可散列的对象(它没有实现hash())。该对象是一个OrderedDict,是一个可变对象,在设计上不可哈希。

作为其他对象类型的示例,该对象类型在设计上是可变的且不可散列,请考虑list以下示例:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

如果您要set()确保唯一性,则必须采取其他方法,尽管您的问题尚不清楚。