In what case would I use a tuple as a dictionary key? [closed]
Asked Answered
A

13

108

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.

Agro answered 21/12, 2009 at 7:1 Comment(1)
You can use tuples but only the ones with immutable elements. If a tuple contains a list (as one of its elements), such a tuple cannot be used as a key. The basic rule is that the data (the tupple) must be hashable.Heiner
P
149

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

Procession answered 21/12, 2009 at 7:14 Comment(3)
Wow. This is very true. I cannot think of any other way of efficiently storing the function values! If your function is very expensive to evaluate, you only do it once, and store the points for later retrieval. +1! Thanks!Agro
Agreed. Also, anywhere you are handling something in memory where you would use a compound key to handle the same thing in a relational database.Milburn
I'm implementing the exact same scenario now. What's the efficiency of search for retrieval? Is it O(1) or O(N)?Enriqueenriqueta
C
39
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
>>>
Coltoncoltsfoot answered 21/12, 2009 at 7:6 Comment(8)
I dont use python much, but wouldnt salaries[('John Smith')] = 99998 be a valid dictionary key?Posology
I agree you can do that, but I would model this data with a class Employee with __init__(self,Firs,Last,Salary), and create an instance for each element in the list. In this case, using the 'tuple as key' trick would appear a bit unnatural to me. What do you think?Agro
of course it would. But then you will have to do extra work if you want to split the key to, say, first and last names.Coltoncoltsfoot
Thanks for your edits, I think the color example is very good, as the general dict[tuple] = f(tuple) mentioned in the answers. I'm a "him" by the way :)Agro
@GrayWizardx, 'John Smith' is a valid key but not necessarily unique, but ('John', 'Smith')Syngamy
@GrayWizardx, ('John Smith') is the same as 'John Smith', which would certainly be valid. Neither is a tuple though...Dorr
Note that you don't need parentheses, tuples are defined by the comma. salaries['John', 'Smith'] = 10000.0 would work too :)Leticia
with python 3.10 (maybe earlier, too), the example given in "Edit 0" works and results in {(range(0, 3), range(10, 13)): 11}Fricassee
T
13

In the context of Machine Learning and Deep Learning, if you're doing hyperparameter search for the best hyperparameters, then using tuples as keys is definitely super useful.

Let's say you're searching for the best hyperparameter combination for learning_rate, regularization_factor, and model_complexity.

Then you can have a dictionary in Python where you make the different combination that these hparams can take as keys and their corresponding weight matrices from the training algorithm as values

hparams_hist = {}
hparams_hist[(0.001, 0.7, 5)] = weight_matrix1
hparams_hist[(0.0001, 0.8, 2)] = weight_matrix2

These weight matrices are further needed to make realtime prediction.

Tasty answered 18/11, 2017 at 16:40 Comment(1)
I find myself doing this a lot! Great example.Faa
S
9

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)]
        ...
    
Syngamy answered 21/12, 2009 at 7:36 Comment(0)
Z
6

I used tuples as dictionary keys in application that compares network devices by geographical location. Since the devices are named similarly for each location, it provides a natural way to know if a device matching that pairing has been seen yet while processing multiples.

i.e.

seen = {}
seen[('abc', 'lax')] = 1
seen[('xyz', 'nyc')] = 1
Zwart answered 21/12, 2009 at 7:37 Comment(0)
H
6

You use tuples as keys when you want to show multiple elements which form a key together.

Eg: {(<x-coordinate>,<y-coordinate>): <indicating letter>}

Here if we use x-coordinate or y-coordinate separately, we wouldn't be representing that point.

Heroworship answered 30/5, 2016 at 4:9 Comment(0)
C
4
a[("John", "Doe")] = "123 Fake Street"
Calorific answered 21/12, 2009 at 7:6 Comment(0)
O
2

I suppose in the case of sorting, there could be merit in using a tuple. For example, suppose the dictionary key represents a sort field (obviously there would be a default sort field to prevent the key from being None). If you needed multiple sort fields, such as the case of sorting by last name, then first name, wouldn't using a tuple as the dictionary key be a good idea?

Sure, such an idea might have limited use, but that doesn't mean it is completely useless.

Overbite answered 21/12, 2009 at 7:22 Comment(0)
U
2

You can use it for funnel analysis if you are building a basic analytics tool.

For example, counting how many people clicked the image3 after hovering on text2.

    funnels = defaultdict(int)
    funnels[('hovered_text2', 'clicked_image3')] += 1
Upwind answered 9/7, 2014 at 20:56 Comment(0)
D
2

You can use it for approx constant time search of a point in search space. For example you can use it for constraint satisfaction problem, where each tuple might contain some constraints. Constraint might be of the form (v1.v2) where color(v1)!=color(v2) for coloring prob, etc. Using tuples as dictionary keys, you will able to tell in constant time whether a permutation satisfies a constraint or not.

Dingbat answered 22/10, 2016 at 7:56 Comment(0)
S
1
def getHash(word):
    result={}
    for i in range(len(word)):
        if word[i] in result:
            result[word[i]]+=1
        else :
            result[word[i]]=1

    return tuple (sorted((result.items())))


def groupAnagrams(words):
    resultHash={}
    for i in range(len(words)):
        s=getHash(words[i].lower())
        #print s
        if s in resultHash :
            l=list(resultHash[s]) 
            l.append(words[i])
            resultHash[s] = l # list(resultHash[s]).append(words[i])  
        else :
            resultHash[s]=[words[i]] # Creating list 

    return resultHash.values()
Septempartite answered 6/5, 2016 at 17:42 Comment(0)
A
0

I think tuples as dictionary keys will be good, if we are storing :-

  1. Some points in the coordinate system.

  2. helps in flag the position of the matrix that you want in the next iteration. for eg:-

    flag = {(0,1): True, (1,0) = False}

Aftonag answered 14/2, 2022 at 0:33 Comment(0)
B
-1

Suppose dictionary contain your subjects and marks.if you have same marks in two subjects so we can use tupple.

D = {}

D[('math','history')] = 74

Boxthorn answered 2/10, 2022 at 10:31 Comment(1)
But then you can only access the mark if you know all the subjects with that mark.Impotence

© 2022 - 2024 — McMap. All rights reserved.