簡體   English   中英

Python從項目列表創建字典鍵

[英]Python creating dictionary key from a list of items

我希望使用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類型:列表” ))-那么從幾個已知屬性生成唯一鍵的規范方法是什么?

使用元組代替列表。 元組是不可變的,可以用作字典鍵:

d[(attrib_a, attrib_b)] = t

括號可以省略:

d[attrib_a, attrib_b] = t

但是,有些人似乎不喜歡這種語法。

使用元組

d[(attrib_a, attrib_b)] = t

那應該很好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM