Python:从字典键中提取键,值对包含特定的Tex

2024-09-29 17:15:03 发布

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

我现在有一本字典,它是这样的:

{OctetString('Ethernet8/6'): Integer(1),
 OctetString('Ethernet8/7'): Integer(2),
 OctetString('Ethernet8/8'): Integer(2),
 OctetString('Ethernet8/9'): Integer(1),
 OctetString('Vlan1'): Integer(2),
 OctetString('Vlan10'): Integer(1),
 OctetString('Vlan15'): Integer(1),
 OctetString('loopback0'): Integer(1),
 OctetString('mgmt0'): Integer(1),
 OctetString('port-channel1'): Integer(1),
 OctetString('port-channel10'): Integer(1),
 OctetString('port-channel101'): Integer(1),
 OctetString('port-channel102'): Integer(1)}

我希望我的字典是这样的:

^{pr2}$

我不确定找到这些键、值对的最佳方法是什么。我真的想要与'\Ethernet(\d*)/(\d*)匹配的任何内容。不过,我不确定最好的解决办法。我的主要目标是匹配所有以太网值,然后进行计数。例如:当dict匹配所有Ethernetx/x之后,我想计算1和2的数量

另外,为什么我迭代字典并打印时只得到Ethernet8/6,但当我打印字典时,我最终得到的是OctetString('Ethernet8/6')?在

for k in snmp_comb: print k
Ethernet2/18
Ethernet2/31
Ethernet2/30
Ethernet2/32
Ethernet8/46

Tags: 字典portintegeroctetstringvlan1channel1loopback0channel10
2条回答

(我将使用与接受答案相同的'Ethernet' in str(key)测试。)

如果您想保留原始dict并将过滤后的版本作为单独的字典,我将使用一个理解:

newdict = {key: value
           for key, value in mydict.items()
           if 'Ethernet' in str(key)}

如果您不想保留原来的dict,也可以删除不需要的条目:

^{pr2}$

得到“OctetString('…')”的原因与此相同:

>>> 'foo'
'foo'
>>> pprint.pprint('foo')
'foo'
>>> print('foo')
foo

前两个测试向您展示了一个可以在源代码中使用的表示,这就是为什么会有引号。这就是repr函数的作用。第三个测试打印的是正常乐趣的值,因此不添加引号。“OctetString('…')”也只是这样一种表示,您可以复制并粘贴到源代码中,然后再次获得实际的OctetString对象,而不是Python字符串对象。我想pprint主要用于开发,在开发中获得完整的repr版本更有用。在

这应该做到:

new_dict = dict()
for key, value in orig_dict.items():
    if 'Ethernet' in str(key):
        new_dict[key] = value

使用print时,python调用OctetString对象上的__str__方法,该方法返回Ethernet8/6。但是,我认为pprint默认为打印对象类型。在

编辑:

stefanpochmann在下面正确地指出,if 'Ethernet' in将匹配包含单词Ethernet的任何字符串。OP在他的帖子中提到过使用regex来匹配Ethernet(\d*)/(\d*),因此这个答案可能不适合任何其他想要解决类似问题的人。在

相关问题 更多 >

    热门问题