Python 字典 : TypeError: unhashable type: 'list'

标签 python hash dictionary

我在从另一个字典开始填充 python 字典时遇到了麻烦。

假设“源”字典有字符串作为键,每个值都有一个自定义对象列表。

我正在创建我的目标字典,就像我创建“源”字典一样,这怎么可能不起作用?

我明白了

TypeError: unhashable type: 'list'

代码:

aTargetDictionary = {}
for aKey in aSourceDictionary:
    aTargetDictionary[aKey] = []
    aTargetDictionary[aKey].extend(aSourceDictionary[aKey])

错误在这一行:aTargetDictionary[aKey] = []

最佳答案

您给出的错误是由于在python中,dictionary keys必须是immutable types(如果key可以改变,就会出现问题),并且列出是一个可变类型。

您的错误表明您尝试使用列表作为字典键,<​​strong>如果您想将列表作为键放入字典中,则必须将列表更改为元组。

根据the python doc :

The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant

关于Python 字典 : TypeError: unhashable type: 'list' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8532146/

相关文章:

Python:在比较它们之前我需要对字典进行排序吗?

python - 如何将 HuggingFace 的 Seq2seq 模型转换为 onnx 格式

string - 选择合适的数据结构(哈希表与后缀树)来索引非常大的相似字符串集

java - Spark TF-IDF 从哈希中获取单词

java - 为什么在Java中2个Object有不同的哈希码,但2个String有相同的哈希码?

c++ - 无论如何要将键,值,值存储到 map 中

python - Pandas:当列中的所有数据均为 NaN 时,从多级索引中删除索引条目(及其所有行)

python - 如何正确关闭两个进程共享的管道?

python - flask-sqlalchemy 对特定表使用 drop_all 和 create_all

Java 哈希码和桶大小 - 关系