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

时间:2011-05-28 23:22:12

标签: 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)

4 个答案:

答案 0 :(得分:7)

实现此目的的最简单方法是使用两个字典:一个将索引映射到您的值,另一个将字符串键映射到相同的对象:

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

答案 1 :(得分: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)

答案 2 :(得分:1)

如果您想为密码命名以获取代码可读性,可以执行以下操作:

ONE, TWO, THREE  = 1, 2, 3

ACTIONS = {
    ONE : value1,
    TWO : value2
}

答案 3 :(得分:1)

Namedtuples很不错:

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