Python从项列表中创建字典键

时间:2013-03-07 17:08:44

标签: python hash dictionary

我希望使用Python字典来跟踪一些正在运行的任务。这些任务中的每一个都有许多属性使它独特,所以我想使用这些属性的函数来生成字典键,这样我就可以使用相同的属性再次在字典中找到它们。如下所示:

class Task(object):
    def __init__(self, a, b):
        pass

#Init task dictionary
d = {}

#Define some attributes
attrib_a = 1
attrib_b = 10

#Create a task with these attributes
t = Task(attrib_a, attrib_b)

#Store the task in the dictionary, using a function of the attributes as a key
d[[attrib_a, attrib_b]] = t

显然这不起作用(列表是可变的,所以不能用作键(“unhashable type:list”)) - 那么生成一个的规范方法是什么?来自几个已知属性的唯一键?

2 个答案:

答案 0 :(得分:5)

使用元组代替列表。元组是不可变的,可以用作字典键:

d[(attrib_a, attrib_b)] = t

括号可以省略:

d[attrib_a, attrib_b] = t

然而,有些人似乎不喜欢这种语法。

答案 1 :(得分:1)

使用元组

d[(attrib_a, attrib_b)] = t

应该可以正常工作

相关问题