Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple value by key

Tags:

python

tuples

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!

like image 374
Mission Avatar asked Jan 04 '12 17:01

Mission


People also ask

What is a key-value tuple?

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.

Does tuple have key and value?

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.

Can a tuple be a key?

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.

How do you find the tuple values in a dictionary?

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.


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

like image 147
NPE Avatar answered Sep 25 '22 22:09

NPE


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

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

like image 24
Koed00 Avatar answered Sep 23 '22 22:09

Koed00