Jon*_*lls 2 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
Run Code Online (Sandbox Code Playgroud)
显然这不起作用(列表是可变的,因此不能用作键("不可用类型:列表")) - 那么从几个已知属性生成唯一键的规范方法是什么?
使用元组代替列表.元组是不可变的,可以用作字典键:
d[(attrib_a, attrib_b)] = t
Run Code Online (Sandbox Code Playgroud)
括号可以省略:
d[attrib_a, attrib_b] = t
Run Code Online (Sandbox Code Playgroud)
但是,有些人似乎不喜欢这种语法.