[Tutor] Accessing a tuple of a dictionary's value

Steven D'Aprano steve at pearwood.info
Wed Aug 22 07:45:16 EDT 2018


On Tue, Aug 21, 2018 at 03:27:46PM -0700, Roger Lea Scherer wrote:

> 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.

Let's do some experimentation. Here's a list:

py> L = [11, 23]
py> print(L[0])  # get the first item
11
py> print(L[1])  # get the second item
23

(Yes, I know that its funny that Python counts from 0, so the second 
item is at index 1...)

That syntax works no matter where the list L comes from. Let's put it in 
a dict:

py> D = {11/23: [11, 23]}
py> print(D)
{0.4782608695652174: [11, 23]}


Now let's try retrieving it:

py> print(D[11/23])
[11, 23]

So where we said "L" before, we can say "D[11/23]" now:

py> print(L[1])
23
py> print(D[11/23][1])
23


But if you're going to do this, I think fractions are nicer.


py> from fractions import Fraction
py> x = Fraction(11, 23)
py> x.numerator
11
py> x.denominator
23
py> float(x)
0.4782608695652174




-- 
Steve


More information about the Tutor mailing list