Question or problem about Python programming:
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:
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.
How to solve the problem:
Solution 1:
Classic Example: You want to store point value as tuple of (x, y)
Solution 2:
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 "", line 1, in TypeError: list objects are unhashable >>>
Solution 3:
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 iskey = (first_name, last_name)
because- It is more readable, shorter and less computation
- It is easier to retrieve the individual values
- Most importantly
key = '%s_%s'%(first_name, last_name)
is wrong and may not give unique keys for all values offirst_name
andlast_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)] ...
Solution 4:
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
Solution 5:
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.
Solution 6:
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.
Solution 7:
a[("John", "Doe")] = "123 Fake Street"
Solution 8:
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.
Solution 9:
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
Solution 10:
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.