Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use both a key and an index for the same dictionary value?

I need an array of data that has a numeric index, but also a human readable index. I need the latter because the numeric indices may change in the future, and I need the numeric indices as a part of a fixed length socket message.

My imagination suggests something like this:

ACTIONS = {
    (0, "ALIVE") : (1, 4, False),
    (2, "DEAD") : (2, 1, True)
}

>ACTIONS[0]
(1, 4, False)
>ACTIONS["DEAD"]
(2, 1, True)
like image 303
Hubro Avatar asked May 28 '11 23:05

Hubro


2 Answers

The simplest way to achieve this is to have two dictionaries: One mapping the indices to your values, and one mapping the string keys to the same objects:

>> actions = {"alive": (1, 4, False), "dead": (2, 1, True)}
>> indexed_actions = {0: actions["alive"], 2: actions["dead"]}
>> actions["alive"]
(1, 4, False)
>> indexed_actions[0]
(1, 4, False)
like image 58
Sven Marnach Avatar answered Oct 18 '22 20:10

Sven Marnach


Use Python 2.7's collections.OrderedDict

In [23]: d = collections.OrderedDict([
   ....:   ("ALIVE", (1, 4, False)),
   ....:   ("DEAD", (2, 1, True)),
   ....: ])

In [25]: d["ALIVE"]
Out[25]: (1, 4, False)

In [26]: d.values()[0]
Out[26]: (1, 4, False)

In [27]: d.values()[1]
Out[27]: (2, 1, True)
like image 30
Wai Yip Tung Avatar answered Oct 18 '22 22:10

Wai Yip Tung