In which case would I use a tuple as a dictionary key?

I studied the difference between lists and tuples (in Python). Obviously, tuples are immutable (values ​​cannot be changed after the initial assignment), while lists are mutable.

The article suggested:

Only immutable elements can be used as dictionary keys and, therefore, only tuples and not lists can be used as keys.

It’s hard for me to think about a situation where I would like to use a tuple as a dictionary key. Can you provide an example of a problem where this would be a natural, effective, elegant or obvious solution?

Edit:

Thanks for your examples. Until now, I believe that caching function values ​​is a very important application.

+48
python list tuples
Dec 21 '09 at 7:01
source share
11 answers

Classic example: you want to save the point value as a tuple (x, y)

+66
Dec 21 '09 at 7:14
source share
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 will have to do additional work to separate the key from the first and last name. What about pointColor[(x, y, z)] = "red" , here the advantage of the tuple key is more noticeable.

I must emphasize that this is not the best practice. In many cases, you'd better create special classes to handle such situations, but Arrieta asked for examples that I gave her (her).

EDIT 0

By the way, each element of the tuple must also be hashed:

 >>> 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 >>> 
+21
Dec 21 '09 at 7:06
source share

I use a tuple a lot of time as a dict , for example.

  • I use them when I need to create a unique key from several values, for example.

    based on first_name , last_name key may be key = '%s_%s'%(first_name, last_name) , but the best way is key = (first_name, last_name) , because

    • This is a more readable, shorter and smaller calculation.
    • Easier to get individual values.
    • Most importantly, key = '%s_%s'%(first_name, last_name) is incorrect and cannot give unique keys for all values ​​of first_name and last_name for example. when values ​​contain _
  • Function result caching

     def func(a1, b1): if (a1,b1) in cache: return cache[(a1,b1)] ... 
+7
Dec 21 '09 at 7:36
source share

I used tuples as dictionary keys in an application that compare network devices by geographic location. Since the devices are named the same for each location, it provides a natural way to find out if a device corresponding to this pairing has been found during multiple processing.

i.e.

 seen = {} seen[('abc', 'lax')] = 1 seen[('xyz', 'nyc')] = 1 
+4
Dec 21 '09 at 7:37
source share

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

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

Here, if we use x-coordinate or y-coordinate separately, we will not represent this point.

+3
May 30 '16 at 4:09
source share

I believe that in the case of sorting, it might be useful to use a tuple. For example, suppose the dictionary key is a sort field (obviously, there would be a default sort field to exclude the None key). If you need several sorting fields, for example, sorting by last name, then first the name will not use the tuple, since the dictionary key would be a good idea?

Of course, such an idea may have limited application, but this does not mean that it is absolutely useless.

+2
Dec 21 '09 at 7:22
source share

You can use it for an approximate time search of a point in the search space. For example, you can use it for a constraint constraint problem, where each tuple may contain some constraints. The restriction can be of the form (v1.v2), where color (v1)! = Color (v2) for the coloring task, etc. Using tuples as dictionary keys, you can indicate for a certain time whether the permutation satisfies the constraints or not.

+2
Oct 22 '16 at 7:56
source share
 a[("John", "Doe")] = "123 Fake Street" 
+1
Dec 21 '09 at 7:06
source share

You can use it to analyze the funnel if you are creating a basic analytics tool.

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

  funnels = defaultdict(int) funnels[('hovered_text2', 'clicked_image3')] += 1 
+1
Jul 09 '14 at 20:56 on
source share
 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() 
+1
May 6 '16 at 17:42
source share

In the context of machine learning and deep learning, if you are searching for hyperparameters for the best hyperparameters, then using tuples as keys is definitely super useful.

Let's say you are looking for the best combination of hyperparameters for learning_rate , regularization_factor and model_complexity .

Then you can have a Python dictionary where you produce a 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 additionally needed for real-time forecasting.

0
Nov 18 '17 at 16:40
source share



All Articles