[英]How can I assign a list in a tuple in a dictionary?
I'm new to python and experimenting a bit but having trouble making a list into a tuple to use as a dictionary key. 我是python的新手并尝试了一下,但是无法将列表放入元组以用作字典键。 Here's an example, which should make it more clear: 这是一个例子,它应该更清楚:
dict_of_lists_values = {}
dict_of_lists_values[('dog', 'cat')] = 10
dict_of_lists_values[('dog1', 'cat1')] = 10
dict_of_lists_values[('dog1', 'cat2')] = 10
dict_of_lists_values
{('dog', 'cat'): 10, ('dog1', 'cat2'): 10, ('dog1', 'cat1'): 10}
This works perfectly, and allows me to have a two values I can use as keys in a dictionary. 这非常有效,并且允许我使用两个值作为字典中的键。 When I try to apply this to a list, I get an error: TypeError: unhashable type: 'list'
当我尝试将其应用于列表时,我收到一个错误: TypeError: unhashable type: 'list'
dict_of_lists_values = {}
a = [22, 39, 0]
b = [15, 38, 12]
dict[(a, b)] = 'please work'
Based on my previous experiment, I think if I convert the list into a string it would work but I want it as it as a list not a string. 基于我之前的实验,我认为如果我将列表转换为字符串它会起作用但我希望它作为列表而不是字符串。
Is this possible? 这可能吗?
在列表上调用tuple()
以创建包含列表中元素的元组。
No. It's not possible to use list
types for dictionary keys. 不可以。字典键不能使用list
类型。 However, you could extend list
, make it hashable, and then use that new type. 但是,您可以扩展list
,使其可以清除,然后使用该新类型。 (Though it's a bit cumbersome.) (虽然有点麻烦。)
class hlist(list):
def __hash__(self):
# Hash it somehow; here, I convert it to a hashable tuple ... and then hash it
return hash(tuple(self))
l1 = hlist([1,2,3])
l2 = hlist([4,5,6])
d = {
l1:"Hi.",
l2:"Hello!"
}
Please note Sven's comment below. 请注意Sven的评论如下。 Mutable keys are dangerous because their hash becomes stale if they are modified. 可变密钥是危险的,因为如果它们被修改,它们的哈希就会变得陈旧。
Dictionaries in Python can only have immutable/hashable keys. Python中的字典只能有不可变/可散列的键。
Strings, numbers, and tuples are immutable, so they can be used as dictionary keys. 字符串,数字和元组是不可变的,因此它们可以用作字典键。 Instances have a unique __hash__()
, so they can also be used. 实例具有唯一的__hash__()
,因此也可以使用它们。 But lists are mutable, so they cannot be used as keys. 但列表是可变的,因此它们不能用作密钥。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.