gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:27:45 32 4
gpt4 key购买 nike

我在从另一个字典开始填充 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 containinglists or dictionaries or other mutable types that are compared byvalue rather than by object identity, the reason being that theefficient implementation of dictionaries requires a key’s hash valueto remain constant

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

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com