2013-03-07 41 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 

這應該做工精細