Hubro
Hubro

Reputation: 59408

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)

Upvotes: 10

Views: 3535

Answers (4)

JBernardo
JBernardo

Reputation: 33407

Namedtuples are nice:

>>> import collections
>>> MyTuple = collections.namedtuple('MyTuple', ('x','y','z'))
>>> t = MyTuple(1,2,3)
>>> t
MyTuple(x=1, y=2, z=3)
>>> t[0]
1
>>> t.x
1
>>> t.y
2

Upvotes: 1

Wai Yip Tung
Wai Yip Tung

Reputation: 18794

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)

Upvotes: 6

AnalyticsBuilder
AnalyticsBuilder

Reputation: 4261

If you want to name your keys for code readability, you can do the following:

ONE, TWO, THREE  = 1, 2, 3

ACTIONS = {
    ONE : value1,
    TWO : value2
}

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 602735

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)

Upvotes: 7

Related Questions