This exercise says a key can be a hashable type like a number or string. Can a tuple be used as a dictionary key?
Answer
Yes, a tuple is a hashable value and can be used as a dictionary key. A tuple would be useful as a key when storing values associated with a grid or some other coordinate type system. The following code example shows a dictionary with keys representing a simple x,y grid system.
No, youâre wrong
This example just shows that the author added some values manually to the dictionary by using tuples as keys of the values
Similar to .append() in lists
As the user above posted you already can create a dictionary like this so that your key:value pair is a tuple mapping to a particular value. Could you explain what other kind of pairing you have in mind?
student_exam_result ={ (âJaneâ , âAshleyâ, âCelineâ) : (80, 90, 65),
(âTimâ, âEmileâ) : [65, 75) }
how can I reach just timâs score. Itâs what I meant when Iâm saying pairing⌠Thank you for answering by the way.
Youâd first need to access the dictionary by key ("Tim", "Emile",) and then index the list or tuple you use next. So student_exam_result[("Tim", "Emile")][0] in this case. That would be a very unfortunate choice of nesting here, there is likely a much better way to organise such values if the use of this dictionary wass to get individual student scores back.
If you look at what youâre asking, is that you want a mapping from (âJaneâ , âAshleyâ, âCelineâ) to (80, 90, 65) so that Jane is associated with 80 etc. This is simply a dictionary! so instead the thing to do is {"Jane":80,"Ashley":90,"Celine":65}, which contains the much simpler and obvious mapping between name and score.
What you are asking to do can be done many different ways using logic. Not the ârightâ way to create dictionaries but can be done. I can think of a couple of other ways to do this but one of them is below. Meanwhile, since keys of a dictionary cannot be duplicated - if any of your values in each first tuple is a duplicate of another value which you are intending to use as a key - I have already made a provision for being able to give a new value. Of course, you could inadvertently enter a NEW value that is also a duplicate and that will require more logic to handle - which I have not written. Hopefully, this piece of code will suffice.
A lot of things to learn here. Hereâs another simple example that could help to get things more clear about using a tuple as a key in a Python dictionary :
coordinates_info = {}
Defining a tuple representing coordinates (latitude, longitude)