Is it possible to get Value out of tuple:
TUPLE = ( ('P', 'Shtg1'), ('R', u'Shtg2'), ('D', 'Shtg3'), )
by calling STR key like P
Python says that only int can be used for this type of 'query'
I can't use loop (too much overhead...)
Thank you!
A tuple1 is a sequence of values much like a list. The values stored in a tuple can be any type, and they are indexed by integers. The important difference is that tuples are immutable. Tuples are also comparable and hashable so we can sort lists of them and use tuples as key values in Python dictionaries.
12.6 Dictionaries and tuples Dictionaries have a method called items that returns a sequence of tuples, where each tuple is a key-value pair. As you should expect from a dictionary, the items are in no particular order.
You can use a tuple as a key if all of the elements contained in the tuple are immutable. (If the tuple contains mutable objects, it cannot be used as a key.) Hence a tuple to be used as a key can contain strings, numbers, and other tuples containing references to immutable objects.
To access the tuple elements from the dictionary and contains them in a list. We have to initialize a dictionary and pass the tuple key and value as an argument. Now to get all tuple keys from the dictionary we have to use the Python list comprehension method.
The canonical data structure for this type of queries is a dictionary:
In [1]: t = ( ...: ('P', 'Shtg1'), ...: ('R', u'Shtg2'), ...: ('D', 'Shtg3'), ...: ) In [2]: d = dict(t) In [3]: d['P'] Out[3]: 'Shtg1'
If you use a tuple, there is no way to avoid looping (either explicit or implicit).
dict(TUPLE)[key]
will do what you want.
There is a little memory overhead, but it's fast.
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