Python从项目列表创建字典键 [英] Python creating dictionary key from a list of items

查看:144
本文介绍了Python从项目列表创建字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用Python字典来跟踪一些正在运行的任务。这些任务中的每一个具有许多属性,使其独特,所以我想使用这些属性的函数来生成字典键,以便我可以通过使用相同的属性再次在字典中找到它们;类似以下内容:

I wish to use a Python dictionary to keep track of some running tasks. Each of these tasks has a number of attributes which makes it unique, so I'd like to use a function of these attributes to generate the dictionary keys, so that I can find them in the dictionary again by using the same attributes; something like the following:

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

显然这不工作列表是可变的,因此不能用作键(不可更改类型:列表)) - 所以从多个已知属性生成唯一键的规范方法是什么?

Obviously this doesn't work (the list is mutable, and so can't be used as a key ("unhashable type: list")) - so what's the canonical way of generating a unique key from several known attributes?

推荐答案

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

Use a tuple in place of the list. Tuples are immutable and can be used as dictionary keys:

d[(attrib_a, attrib_b)] = t

括号可以省略:

d[attrib_a, attrib_b] = t

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

However, some people seem to dislike this syntax.

这篇关于Python从项目列表创建字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆