pythontuples

Tuple value by key


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!


Solution

  • 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).