Tuple value by key

Question:

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!

Asked By: Mission

||

Answers:

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

Answered By: NPE

You want to use a dictionary instead.

d = { 'P': 'Shtg1', 'R': u'Shtg2', 'D':'Shtg3' }

And then you can access the key like so:

d['P'] # Gets 'Shtg1'
Answered By: Makoto

Instead of moving to full dictionaries you can try using a named tuple instead. More information in this question.

Basically you define tags for the fields and then are able to refer to them as value.tag1, etc.

Quoting the docs:

Named tuple instances do not have per-instance dictionaries, so they
are lightweight and require no more memory than regular tuples.

Answered By: Eduardo Ivanec

To elaborate on Eduardo’s answer with some code from the python shell.

>>> from collections import namedtuple
>>> MyType = namedtuple('MyType', ['P', 'R', 'D'])
>>> TUPLE = MyType(P='Shtg1', R=u'Shtg2', D='Shtg3')
>>> TUPLE
MyType(P='Shtg1', R=u'Shtg2', D='Shtg3')

>>> TUPLE.P
'Shtg1'

>>> TUPLE.R
u'Shtg2'

>>> TUPLE.D
'Shtg3'

>>> TUPLE[0:]
('Shtg1', u'Shtg2', 'Shtg3')

Remember that tuples are immutable, and dictionaries are mutable. If you want immutable types, namedtuple might be the way to go.

Answered By: cod3monk3y

dict(TUPLE)[key] will do what you want.

There is a little memory overhead, but it’s fast.

Answered By: Koed00
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.