Python不可分类型:'OrderedDict' [英] Python unhashable type: 'OrderedDict'

查看:137
本文介绍了Python不可分类型:'OrderedDict'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太了解以下概念:

  TypeError:不可分类型:'OrderedDict'

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

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

文件myFile.py,第102行,diff
l1s = set(var1)
TypeError:unhashable type :'OrderedDict'

如何行 102 在上面的代码中抛出这样的异常?

解决方案

一些数据结构(最引人注目的是 dict s和 set s)需要它们包含的对象(在字典的情况下是键,在se的情况下的项ts)来实现 __ hash __() magic方法,所以调用 hash(obj)返回一个值。 p>

这是优化结构所必需的,并且与不变性一起保证包含对象的唯一性。



在你的case var1 包含一些不是哈希的对象(它不实现 hash())。这个对象是一个 OrderedDict ,它是一个可变的对象,不可设计的哈希。



另外一种可变的,不可设计的哈希的对象,考虑列表,这个例子:

 >>> L = [1,2,3] 
>>> set([L])
追溯(最近的最后一次调用):
文件< stdin>,第1行,< module>
TypeError:不可分类型:'list'
>>> hash(L)
追溯(最近的最后一次调用):
文件< stdin>,第1行,< module>
TypeError:unhashable类型:'list'

如果您使用 set()以确保唯一性,那么您必须以其他方式去,尽管您的问题不清楚。


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?

解决方案

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.

这篇关于Python不可分类型:'OrderedDict'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆