Escualo Escualo - 1 month ago 7
Python Question

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.

Answer

Classic Example: You want to store point value as tuple of (x, y)

Comments