简体   繁体   中英

Python creating dictionary key from a list of items

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

The parentheses can be omitted:

d[attrib_a, attrib_b] = t

However, some people seem to dislike this syntax.

Use a tuple

d[(attrib_a, attrib_b)] = t

That should work fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM