无法散列的类型:字典中的“列表" [英] Unhashable type: 'list' in dictionary

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

问题描述

我写了一些代码来从第二个字典中获取新值并添加到新字典中.

I wrote some code to somewhat grab new values from a second dictionary and add to a new dictionary.

这是两个字典:

a = {armani: jeans, dolce: gabbana}
b = {jeans: robo, jobs: versace}

这是代码: {k:b[v] for k,v in a.items() if v in b}

但是,出现以下错误:unhashable type: 'list'我了解这可能是因为我的b[v]值类似于[[20], [30], [35]]

However, I am getting the following error: unhashable type: 'list' I understand that it might be because my values for b[v] are like [[20], [30], [35]]

在过去的几个小时里,我的头一直发疯.我敢肯定它太小了

My head has been going crazy for the past few hours. I am sure it is something so small

推荐答案

它并不是那么小.您需要先了解一些概念,然后才能继续进行操作.

It's not something so small. You need to understand some concepts before continuing with your process.

字典允许您使用键(例如字符串或整数)而不是索引(例如列表)来访问其值,对吗?嗯,应该有一种机制来实现这一目标,即所谓的哈希.

Dictionaries allow you to access their values with keys such as strings or integers rather than indexes (like lists) right ? Well there should be a mechanism behind the curtains to make this happen which is called a hash.

每次将key:value对放入字典中时,都会为该key计算一个哈希值.对于不可变对象(创建后无法更改,只能重新创建的对象),对于相同的字符串或整数或其他不可变对象,哈希值始终相同,这就是字典使用键访问其值的方式.

Every time you put a key:value pair inside a dictionary, a hash value is calculated for that key. With immutable objects (Objects that cannot be changed after creation, that can only be re-created), the hash value always the same for the same string or integer or other immutable objects, this is how the dictionary accesses its values with a key.

相反,不能对可变对象进行哈希处理.因此不适合用作字典中的键. list是其中之一.

Mutable objects on the other hand, can't be hashed. Therefore is not fit to be used as a key inside a dictionary. And list is one of them.

如果必须的话,可以将列表转换为元组,以便在字典中将其用作键.

If you must, you can convert the list into a tuple to use it in a dictionary as a key.

lst = [1, 2, 3]
tup = tuple(lst)

请记住,创建后不能更改元组的元素,例如;

Keep in mind that you can't change the elements of a tuple after creation, such as;

tup[0] = 1

这就是为什么它是不可变的.如果您需要更改其值,则只能将其替换为另一个元组.

Which is why it is immutable. You can only replace it with another tuple, if you require its values to be changed.

注意:如果需要将元组用于哈希(这会使它可变),则元组也不能包含列表作为元素.

Note: The tuple cannot contain lists as elements as well, if it is required to be used for hashing (Which would make it mutable).

这篇关于无法散列的类型:字典中的“列表"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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