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

Alan Gauld alan.gauld at yahoo.co.uk
Wed Aug 22 06:38:01 EDT 2018


On 21/08/18 23:27, Roger Lea Scherer wrote:

> I can't find anything in StackOverflow or Python documentation specifically
> about this. They talk about accessing a list or a tuple or a dictionary,
> but not when the value is a tuple or list.

The value is irrelevant youi access the value in
exactly the same way  regardless of data:

data = dictionary[key]

Now you can access data's elements as normal

print(data[0])

Of course you can combine those into a single line:

print(dictionary[key][0])

> fractions.values([0])
> which gives a TypeError: values() takes no arguments (1 given)

values returns a list(*) of all the values in your dict.
In your case a list of tuples. But because it returns
all of them it requires no arguments.

(*)Not strictly a list, but the v3 implementation of this
is a bit weird so we'll ignore the niceties for now!

> fractions.values()[0]
> which gives a TypeError: 'dict_values' object does not support indexing

As per the note it doesn't return a real list
(although you can convert it) but that doesn't matter
since even if what you are trying worked it would return
the first tuple, not the first integer of the tuple.

> 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]}

values[0.5][0]

However remember that floats are not exact representations
so if you use a calculated value as your key it may not exactly
match your given key and it won't find the item!

>>> d = {}
>>> d[0.3] = (3,10)
>>> d[0.3]
(3, 10)
>>> d[0.1+0.2]
Traceback (most recent call last):
  File "<pyshell#86>", line 1, in <module>
    d[0.1+0.2]
KeyError: 0.30000000000000004
>>>
>>> d[ round(0.1+0.2, 2) ]
(3, 10)
>>>

Just something to be aware of.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list