Python不可验证(!)字典键

2024-05-19 07:23:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有来自机器的数据(通过pexpect),我使用regex将其解析到像这样的字典中

for line in stream:
    if '/' in line:
        # some matching etc which results in getting the
        # machine name, an interface and the data for that interface
        key=str(hostname)+":"+r.groups()[0][0:2]+r.groups()[2]
        dict[key]=str(line[3])

这一切都很好,当我读回来的时候,我得到了很多这样的台词

^{pr2}$

<data>是一个字符串或整数

我现在意识到接口可以存在多个数据,在这种情况下,我每次遇到键时都会重写它的值。我想做的是使键唯一的方式,以突出的事实,多个信息存在于该接口。E、 如果fe3有

machine1:fe0:3 <data> <data> <data>
machine1:fe1:4 <data> <data> <data> <data>

为此,我不介意单个实例后面有一个1来告诉我这一点。
希望这是清楚的,有人可以指出我的正确方向-非常感谢


Tags: the数据keyin机器fordata字典
2条回答

可以为每个键创建一个列表,其中包含该键的所有值:

d = collections.defaultdict(list)
for line in stream:
    if '/' in line:
        #.....
        key =  str(hostname)+":"+r.groups()[0][0:2]+r.groups()[2]
        value = str(line[3])
        d[key].append(value)

编辑:如果您希望键/值与问题中指定的完全一致,则可以执行以下操作:

^{pr2}$

我在这里使用了' '.join()将这些值连接到一个字符串中—从您的问题中看不出这是否是您想要的。在

我建议你不要用这种方式去获取个人价值观。在

for (lineno, line) in enumerate(stream):
    if '/' in line:
        # some matching etc which results in getting the
        # machine name, an interface and the data for that interface
        key=str(hostname)+":"+r.groups()[0][0:2]+r.groups()[2]
        dict[key + ":" + lineno]=str(line[3])

您不会以这种方式平滑地增加它,但是每个字典键都是唯一的,并且与每个hostname+接口对相关联的数字将增加。您可以通过将最后一行更改为dict[key + ":" + ('%06d' % (lineno,))=str(line[3]),使键在词汇上可排序

相关问题 更多 >

    热门问题