Query Python dictionary for retrieving values ​​from a tuple

Say I have a Python dictionary, but the values ​​are a tuple:

eg.

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

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

I could do this with .iteritems() , for example, like:

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

however, is there a more direct approach?

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

eg.

dict[Key1] = ValZ1 instead of what I am now getting is that dict[Key1] = (ValX1, ValY1, ValZ1) , which is not callable ...

Any tips?

+6
source share
3 answers

Just keep on indexing:

 >>> D = {"Key1": (1,2,3), "Key2": (4,5,6)} >>> D["Key2"][2] 6 
+7
source

Use 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 element of the tuple. But this can cause problems if you use the gettext module for applications with multiple languages, as this model sets up a global function called _ .

Since tuples are immutable, you cannot set only one element, for example

 d[key][0] = x 

First you need to unpack:

 x, y, z = d[key] d[key] = x, newy, z 
+4
source

Using a generator expression!

 for val in (x[2] for x in dict): print val 

You do not need to use iteritems because you are only looking at values.

+1
source

Source: https://habr.com/ru/post/897771/


All Articles