Python从项目列表创建字典键

Python从项目列表创建字典键,python,hash,dictionary,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 #Cr

我希望使用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”)-那么从几个已知属性生成唯一键的标准方法是什么呢?

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

d[(attrib_a, attrib_b)] = t
括号可以省略:

d[attrib_a, attrib_b] = t
然而,有些人似乎不喜欢这种语法。

使用元组

d[(attrib_a, attrib_b)] = t
这应该行得通