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?
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”.
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.
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.
Just keep indexing:
>>> D = {"Key1": (1,2,3), "Key2": (4,5,6)}
>>> D["Key2"][2]
6
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With