2

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Use a tuple

d[(attrib_a, attrib_b)] = t

That should work fine

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.