python – In what case would I use a tuple as a dictionary key?

python – In what case would I use a tuple as a dictionary key?

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 youll 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
>>>

python – In what case would I use a tuple as a dictionary key?

I use tuple lots of time as dict key e.g.

  • I do use them when I have to create a unique key from multiple values e.g.

    based on first_name, last_name key could be key = %s_%s%(first_name, last_name) but better way is key = (first_name, last_name) because

    1. It is more readable, shorter and less computation
    2. It is easier to retrieve the individual values
    3. Most importantly key = %s_%s%(first_name, last_name) is wrong and may not give unique keys for all values of first_name and last_name e.g. when values contain _
  • Caching the results of a function

    def func(a1, b1):
        if (a1,b1) in cache: return cache[(a1,b1)]
        ...
    

Leave a Reply

Your email address will not be published. Required fields are marked *