简体   繁体   English

“类型错误:不可散列的类型:dict” python 错误

[英]“Type Error: unhashable type: dict” python error

This is currently not finished but I'm trying to add a weapon to an “weapon_inventory” and whenever I try this error pops up.这目前还没有完成,但我正在尝试将武器添加到“weapon_inventory”中,并且每当我尝试时都会弹出此错误。 I'm a beginner to python so if you know how to fix this try explain it pretty simple so I can understand it and improve.我是 python 的初学者,所以如果您知道如何解决此问题,请尝试将其解释得很简单,以便我可以理解并改进。

weapon_inventory = {}

weapon_found = "Boss Weapon"
weapon_inventory.update({weapon_found: {"name": weapon_found, "durability": 100}})
print("Inventory: ", ", ".join(weapon_inventory))

Your code snippet is working for me on Python 3.8.10.您的代码片段在 Python 3.8.10 上为我工作。 But to understand the error you said you are getting, you should learn how dictionaries work.但是要了解您所说的错误,您应该了解字典的工作原理。

In Python, you can say there are two kinds of datatypes.在 Python 中,可以说有两种数据类型。 Hashable and Non-Hashable.可散列和不可散列。 Hashable are those which are immutable (whose value doesn't change with time) like integer, string, tuple, etc. And non-hashable are those which are mutable (whose value might change with time) like lists, dicts, etc.可散列是不可变的(其值不随时间变化),如 integer、字符串、元组等。不可散列是可变的(其值可能随时间变化),如列表、字典等。

In a dictionary, your "Key" should be a hashable python datatype only.在字典中,您的“密钥”应该是一个可散列的 python 数据类型。 Means, you can't use lists, dicts, or sets, as your "Keys".意味着,您不能使用列表、字典或集合作为您的“键”。 If you try using a non-hashable datatype as your dict keys, then you'll get the error you have mentioned in the question title: TypeError: unhashable type: 'dict'如果您尝试使用非哈希数据类型作为您的 dict 键,那么您将收到您在问题标题中提到的错误: TypeError: unhashable type: 'dict'

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

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