Python TypeError: unhashable type: 'dict', 当 dict 用作另一个 dict 的键时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4531941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: unhashable type: 'dict', when dict used as a key for another dict
提问by Frias
I have this piece of code:
我有这段代码:
for element in json[referenceElement].keys():
When I run that code, I get this error:
当我运行该代码时,出现此错误:
TypeError: unhashable type: 'dict'
类型错误:不可散列的类型:'dict'
What is the cause of that error and what can I do to fix it?
该错误的原因是什么,我该怎么做才能解决它?
采纳答案by moinudin
From the error, I infer that referenceElementis a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).
从错误中,我推断那referenceElement是一本字典(见下面的repro)。字典不能被散列,因此不能用作另一个字典的键(或者它本身!)。
>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'
You probably meant either for element in referenceElement.keys()or for element in json['referenceElement'].keys(). With more context on what types jsonand referenceElementare and what they contain, we will be able to better help you if neither solution works.
您的意思可能是for element in referenceElement.keys()或for element in json['referenceElement'].keys()。有了更多关于什么类型json、referenceElement是什么以及它们包含什么的上下文,如果两种解决方案都不起作用,我们将能够更好地帮助您。
回答by dshipper
What it seems like to me is that by calling the keys method you're returning to python a dictionary object when it's looking for a list or a tuple. So try taking all of the keys in the dictionary, putting them into a list and then using the for loop.
在我看来,通过调用 keys 方法,当 Python 查找列表或元组时,您将返回一个字典对象。因此,尝试获取字典中的所有键,将它们放入一个列表中,然后使用 for 循环。

