Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query Python dictionary to get value from tuple

Let's say that I have a Python dictionary, but the values are a tuple:

E.g.

dict = {"Key1": (ValX1, ValY1, ValZ1), "Key2": (ValX2, ValY2, ValZ2),...,"Key99": (ValX99, ValY99, ValY99)}

and I want to retrieve only the third value from the tuple, eg. ValZ1, ValZ2, or ValZ99 from the example above.

I could do so using .iteritems(), for instance as:

for key, val in dict.iteritems():
       ValZ = val[2]

however, is there a more direct approach?

Ideally, I'd like to query the dictionary by key and return only the third value in the tuple...

e.g.

dict[Key1] = ValZ1 instead of what I currently get, which is dict[Key1] = (ValX1, ValY1, ValZ1) which is not callable...

Any advice?

like image 412
jsnider Avatar asked Sep 21 '11 17:09

jsnider


People also ask

Can we use tuple as value in dictionary Python?

Using Tuples as Keys in Dictionaries. Because tuples are hashable and lists are not, if we want to create a composite key to use in a dictionary we must use a tuple as the key. Write code to create a dictionary called 'd1', and in it give the tuple (1, 'a') a value of “tuple”.

Can we convert tuple into dictionary?

In Python, use the dict() function to convert a tuple to a dictionary. A dictionary object can be created with the dict() function. The dictionary is returned by the dict() method, which takes a tuple of tuples as an argument. A key-value pair is contained in each tuple.

How do I fetch a dictionary value?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.


2 Answers

Just keep indexing:

>>> D = {"Key1": (1,2,3), "Key2": (4,5,6)}
>>> D["Key2"][2]
6
like image 136
Mark Tolonen Avatar answered Oct 03 '22 18:10

Mark Tolonen


Use tuple unpacking:

for key, (valX, valY, valZ) in dict.iteritems():
       ...

Often people use

for key, (_, _, valZ) in dict.iteritems():
       ...

if they are only interested in one item of the tuple. But this may cause problem if you use the gettext module for multi language applications, as this model sets a global function called _.

As tuples are immutable, you are not able to set only one item like

d[key][0] = x

You have to unpack first:

x, y, z = d[key]
d[key] = x, newy, z
like image 43
rocksportrocker Avatar answered Oct 03 '22 17:10

rocksportrocker