In what case would I use a tuple as a dictionary key?
I was studying the difference between lists and tuples (in Python). An obvious one is that tuples are immutable (the values cannot be changed after initial assignment), while lists are mutable.
A sentence in the article got me:
Only immutable elements can be used as dictionary keys, and hence only tuples and not lists can be used as keys.
I have a hard time thinking of a situation where I would like to use a tuple as a dictionary key. Can you provide an example problem where this would be the natural, efficient, elegant, or obvious solution?
Edit:
Thanks for your examples. So far I take that a very important application is the caching of function values.
Classic Example: You want to store point value as tuple of (x, y)
salaries = {}
salaries[('John', 'Smith')] = 10000.0
salaries[('John', 'Parker')] = 99999.0
EDIT 1
Of course you can do salaries['John Smith'] = whatever
, but then you'll have to do extra work to separate the key into first and last names. What about pointColor[(x, y, z)] = "red"
, here the benefit of tuple key is more prominent.
I must stress out that this is not the best practice. In many cases you better create special classes to handle situations like that, but Arrieta asked for examples, which I gave her (him).
EDIT 0
By the way, each tuple element has to be hashable too:
>>> d = {}
>>> t = (range(3), range(10, 13))
>>> d[t] = 11
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>>