2013-03-07 38 views
2

我希望使用Python字典跟踪一些正在运行的任务。这些任务中的每一个都有许多属性,这使得它是唯一的,所以我想使用这些属性的函数来生成字典密钥,以便我可以通过使用相同的属性再次在字典中找到它们;类似如下: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类型:列表”)) - 有啥规范从几个已知属性生成唯一密钥的方法?

回答

5

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

d[(attrib_a, attrib_b)] = t 

括号可以省略:

d[attrib_a, attrib_b] = t 

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

1

使用元组

d[(attrib_a, attrib_b)] = t 

这应该做工精细