我偶然发现了this question并想知道为什么我不能这样做:
# this does not work
pipeline = {
{"resample" : {"type" : "trans", "name" : "resample", "kwargs" : {"rule" : "1min"}}}
}
pipeline
正如它给出的:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-7305ba79e664> in <module>
1 pipeline = {
----> 2 {"resample" : {"type" : "trans", "name" : "resample", "kwargs" : {"rule" : "1min"}}}
3 }
4 pipeline
TypeError: unhashable type: 'dict'
但我可以做到这一点:
# this does work
pipeline = dict()
pipeline["resample"] = {"type" : "trans", "name" : "resample", "kwargs" : {"rule" : "1min"}}
pipeline
给出:
{'resample': {'type': 'trans', 'name': 'resample', 'kwargs': {'rule': '1min'}}}
我只是很好奇,因为感觉我在最终结果方面做了同样的事情,但只是不确定为什么第一种方法失败,但第二种方法可以。
最佳答案
因为你不能将字典项目保留在集合中。当您尝试声明时
pipeline = {
{"resample" : {"type" : "trans", "name" : "resample", "kwargs" : {"rule" : "1min"}}}
}
您基本上是在尝试创建一个集合,其第一项是字典:
{"resample" : {"type" : "trans", "name" : "resample", "kwargs" : {"rule" : "1min"}}}
但是,您始终可以单独将管道分配给该字典。集合要求项目是可散列的。字典本身在 python 中不可散列。您可以在终端中使用任何字典尝试此操作。尝试 hash({1: 'a', 2: 'b'})
,它应该会给出相同的 TypeError: unhashable type: 'dict'
错误。
关于Python unhashable type dict 关于为什么这两种方法有不同结果的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56595860/