我在从另一个字典开始填充 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/