Python字典:TypeError:不可散列的类型:'list' [英] Python dictionary : TypeError: unhashable type: 'list'

查看:32
本文介绍了Python字典:TypeError:不可散列的类型:'list'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having troubles in populating a python dictionary starting from another dictionary.

假设源"字典将字符串作为键,并且每个值都有一个自定义对象列表.

Let's assume that the "source" dictionary has string as keys and has a list of custom objects per value.

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

I'm creating my target dictionary exactly as I have been creating my "source" dictionary how is it possible this is not working ?

我明白了

TypeError: unhashable type: 'list'

代码:

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

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

推荐答案

你给出的错误是因为在python中,字典key必须是不可变类型(如果key可以改变就会有问题),并且list是可变类型.

The error you gave is due to the fact that in python, dictionary keys must be immutable types (if key can change, there will be problems), and list is a mutable type.

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

Your error says that you try to use a list as dictionary key, you'll have to change your list into tuples if you want to put them as keys in your dictionary.

根据python文档:

唯一不能作为键接受的值类型是包含比较的列表或字典或其他可变类型值而不是对象标识,原因是字典的有效实现需要一个键的哈希值保持不变

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:不可散列的类型:'list'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆