简体   繁体   English

Python不可用类型:'OrderedDict'

[英]Python unhashable type: 'OrderedDict'

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? 102行如何在上面的代码中抛出这样的异常?

Some data structures (most notably dict s and set s) 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. 一些数据结构(最值得注意的是dictset )需要它们包含的对象(字典中的键,集合中的项)来实现__hash__()魔术方法,以便调用hash(obj)返回一个值。

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() ). 在你的情况, var1包含一些对象不是可哈希 (它没有实现hash() This object is an OrderedDict , which is a mutable object and is not hashable by design. 该对象是OrderedDict ,它是一个可变对象,并且不可设计。

As an example of an other object type which is mutable and not hashable by design, consider list and this example: 作为可变且不可设计的其他对象类型的示例,请考虑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'

If you're using set() to ensure uniqueness then you must go some other way, though it's not clear from your question. 如果你使用set()来确保唯一性,那么你必须采取其他方式,尽管你的问题并不清楚。

dict(including OrderedDict) in python are mutable containers. python中的dict(包括OrderedDict)是可变容器。

If a dict was hashed, its hash value would be changed as long as you changed the dict's contents. 如果dict被哈希,只要你更改了dict的内容,它的哈希值就会改变。

Sets in python are based on hashes. python中的集合基于哈希。 OrderedDicts are not hashable. OrderedDicts不可清除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM