[Tutor] Accessing a tuple of a dictionary's value
Mats Wichmann
mats at wichmann.us
Wed Aug 22 12:27:26 EDT 2018
On 08/21/2018 04:27 PM, Roger Lea Scherer wrote:
> So I'm trying to divide fractions, technically I suppose integers. So, for
> instance, when the user inputs a 1 as the numerator and a 2 as the
> denominator to get the float 0.5, I want to put the 0.5 as the key in a
> dictionary and the 1 and the 2 as the values of the key in a list {0.5: [1,
> 2]}, hoping to access the 1 and 2 later, but not together. I chose a
> dictionary so the keys won't duplicate.
...
> Both of these errors sort of make sense to me, but I can't find a way to
> access the 1 or the 2 in the dictionary key:value pair {0.5: [1, 2]}
To add a little bit to the discussion that has already taken place:
I'm really unfond of accessing members of a collection by numeric index.
Perhaps unreasonably so! It always makes you stop and think when you
swing back and look at code later. foo[1]? what was that second element
again?
Fortunately, Python will let you "unpack" a tuple or list at assignment
time, where you provide a number of variables on the left hand side that
is equal to the length of the tuple on the right hand side.
Setting aside the floating point consideration here by using a string
instead, let's say we have a dictionary with two keys, which have a
value which is a tuple as you've described it, numerator and demoninator:
>>> d = {"half": (1, 2), "twothirds": (2, 3)}
you fetch the value by indexing by key, like d["twothirds"]
when doing so, you can immediately assign the value to variables that
have meaning to you, like this:
>>> numer, denom = d["twothirds"]
>>> print(numer, denom)
(2, 3)
I think that's nicer than: numer = d["twothirds][0]
More information about the Tutor
mailing list