如何为同一字典值使用键和索引?

Hub*_*bro 10 python python-2.7

我需要一个具有数字索引的数据数组,但也需要一个人类可读的索引.我需要后者,因为数字索引将来可能会改变,我需要数字索引作为固定长度套接字消息的一部分.

我的想象力表明这样的事情:

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

>ACTIONS[0]
(1, 4, False)
>ACTIONS["DEAD"]
(2, 1, True)
Run Code Online (Sandbox Code Playgroud)

Sve*_*ach 7

实现这一目标最简单的方法是有2点字典:一个映射的索引你的价值观,和一个映射的字符串键,以相同的对象:

>> 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)
Run Code Online (Sandbox Code Playgroud)

  • 但是有一些问题:如果将其中一个键更改为新值,则indexed_actions和actions不会保持同步,即使actions ["alive"]是indexed_actions [0]. (2认同)

Wai*_*ung 6

使用Python 2.7的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)
Run Code Online (Sandbox Code Playgroud)