设置为字典键 [英] set as dictionary key

查看:66
本文介绍了设置为字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中运行了以下代码,但收到标题为"TypeError:unhashable type:'set'的错误.我想把那个钥匙变成一个清单.我该如何解决这个错误?

I ran the below line of code in Python but got an error titled "TypeError: unhashable type: 'set' ". I want to turn that key to a list. How can I solve this error?

dictionary = {
    'a' : [[1,2,3],[4,5,6],[7,8,9]],
    'b' : 2,
    {100} : 3
}
print(dictionary['a'][1][2])

推荐答案

字典中的键必须是可哈希的(或更优的是:不可变的). set 对象是可变(如列表)

keys of a dictionary must be hashable (or better: immutable). set objects are mutable (like lists)

您可以改用 frozenset

dictionary = {
    'a' : [[1,2,3],[4,5,6],[7,8,9]],
    'b' : 2,
    frozenset({100}) : 3
}

frozenset set 是不可变的.这是内置类型.现在,您甚至可以通过传递由具有重复条目/列表中任何条目的列表/元组组成的冻结集来获取值,它仍然会找到该值

A frozenset is a set that is immutable. It's a builtin type. Now you can get the value even by passing a frozenset made of lists/tuples with duplicate entries/any order in the list and it still finds the value

>>> dictionary[frozenset((100,100))]
3

这篇关于设置为字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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