Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 930
Escualo Avatar asked Dec 21 '09 07:12

Escualo


People also ask

How is tuple used in dictionary?

To access the tuple elements from the dictionary and contains them in a list. We have to initialize a dictionary and pass the tuple key and value as an argument. Now to get all tuple keys from the dictionary we have to use the Python list comprehension method.

Can a tuple be a dictionary value?

Literals and immutable types like numbers, strings, and tuples are all hashable, and can therefore serve as keys in dictionaries.


1 Answers

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

like image 145
Imran Avatar answered Sep 21 '22 18:09

Imran